I'm a novice at SQL. Kindly help .
I have two tables like this:
CREATE TABLE [tblCg](
[c_id] [char](1) NOT NULL
CONSTRAINT [pk_tblCg] PRIMARY KEY NONCLUSTERED
(
[c_id] ASC
)
)
CREATE TABLE [tblTR](
[c_id] [char](1) NOT NULL,
[q] [char](2) NOT NULL,
[tdate] [varchar](12) NULL,
[t_res] [char](4) NULL
CONSTRAINT [pk_tblTR] PRIMARY KEY NONCLUSTERED
(
[c_id] ASC,
[q] ASC
)
)
INSERT INTO [tblCg] VALUES ('1')
INSERT INTO [tblCg] VALUES ('2')
INSERT INTO [tblCg] VALUES ('3')
INSERT INTO [tblCg] VALUES ('4')
/* Date is the same for a given c_id, may differ across c_id's */
INSERT INTO [tblTR] VALUES ('1', 'R1', getdate(), '1.01')
INSERT INTO [tblTR] VALUES ('1', 'R2', getdate(), '55.6')
INSERT INTO [tblTR] VALUES ('1', 'R3', getdate(), '48.2')
INSERT INTO [tblTR] VALUES ('1', 'R4', getdate(), '9.44')
INSERT INTO [tblTR] VALUES ('2', 'R1', DATEADD(month, 1, getdate()), '5.26')
INSERT INTO [tblTR] VALUES ('2', 'R2', DATEADD(month, 1, getdate()), '678')
INSERT INTO [tblTR] VALUES ('2', 'R3', DATEADD(month, 1, getdate()), '48.7')
INSERT INTO [tblTR] VALUES ('2', 'R4', DATEADD(month, 1, getdate()), '4.26')
INSERT INTO [tblTR] VALUES ('3', 'R1', DATEADD(month, 2, getdate()), '6.23')
INSERT INTO [tblTR] VALUES ('3', 'R2', DATEADD(month, 2, getdate()), '2465')
INSERT INTO [tblTR] VALUES ('3', 'R3', DATEADD(month, 2, getdate()), '52.5')
INSERT INTO [tblTR] VALUES ('3', 'R4', DATEADD(month, 2, getdate()), '61.2')
INSERT INTO [tblTR] VALUES ('4', 'R1', DATEADD(month, 3, getdate()), '5.12')
INSERT INTO [tblTR] VALUES ('4', 'R2', DATEADD(month, 3, getdate()), '654')
INSERT INTO [tblTR] VALUES ('4', 'R3', DATEADD(month, 3, getdate()), '8.54')
INSERT INTO [tblTR] VALUES ('4', 'R4', DATEADD(month, 3, getdate()), '8.16')
I need an output like this. https://i.stack.imgur.com/VbWpB.jpg
Each c_id has one date (tdate) and up to a maximum of 4 results (t_res). Output can contain NULLs, if there is no corresponding data, as the front-end report can handle them. (similar to OUTER JOINs). Kindly let me know if you need any more information.
My main requirement here is to get 4 rows of [tblTR] as 4 columns + 1 date, for each c_id.
EDIT: Since this question was marked as duplicate and redirected to a URL that almost answers my question, I tried to incorporate the same to my query but it returns only one row. This is the query I came up with, on the same lines as in the example at the redirected URL.
select R1, R2, R3, R4
from
(
select [t_res], [q]
from [tblTR]
) d
pivot
(
max(t_res)
for [q] in (R1, R2, R3, R4)
) piv;