I have following data in a table, in table each group contain two values for ON/OFF in two rows. I want to convert rows into new columns "Col1=>Col1_Status_ON/OFF" new name based on status
here is the detail:
====================================================
| Group | DateTime | Status | Col1 | Col2 |
====================================================
| Group1 | 01-Jan-2019 | ON | 101 | 102 |
| Group1 | 01-Jan-2019 | OFF | 201 | 202 |
| Group2 | 01-Jan-2019 | ON | 301 | 302 |
| Group2 | 01-Jan-2019 | OFF | 401 | 402 |
| Group3 | 01-Jan-2019 | ON | 501 | 502 |
| Group4 | 01-Jan-2019 | OFF | 601 | 602 |
====================================================
I want query that return as follows
=======================================================================================
| Group | DateTime |Col1_Satus_ON|Col1_Satus_OFF|Col2_Status_ON|Col2_Status_OFF|
=======================================================================================
| Group1 | 01-Jan-2019| 101 | 201 | 102 | 202 |
| Group2 | 01-Jan-2019| 301 | 401 | 302 | 402 |
| Group3 | 01-Jan-2019| 501 | 601 | 502 | 602 |
=======================================================================================
below are the SQL to generate table data.
DROP TABLE IF EXISTS dbo.#MyTable;
SELECT CONVERT(VARCHAR(100),'')[Group], GETDATE()[DateTime],
CONVERT(VARCHAR(100),'')[Status],(0)[Col1],(0)[Col2]
INTO #MyTable WHERE 1=2;
INSERT INTO #MyTable ([Group],[Datetime],[Status],[Col1],[Col2])
SELECT 'Group1','01-Jan-2019 01:02:03','ON' ,101,102 UNION
SELECT 'Group1','01-Jan-2019 01:02:03','OFF',201,202 UNION
SELECT 'Group2','01-Jan-2019 01:02:03','ON' ,301,302 UNION
SELECT 'Group2','01-Jan-2019 01:02:03','OFF',401,402 UNION
SELECT 'Group3','01-Jan-2019 01:02:03','ON' ,501,502 UNION
SELECT 'Group3','01-Jan-2019 01:02:03','OFF',601,602;
SELECT * FROM #MyTable;
please suggest the query,