2

I am trying to split one datefield column into three target columns, depending on a status column:

My table1 is as follows:

**id    status    DateField**
   1     A       1/5/2018
   2     B       1/6/2018
   3     C       1/7/2018

So I am trying to convert this data to the following format (Timestamps tracking when an id entered a certain stage)

id    Timestamp_A  Timestamp_B    Timestamp_C
1      1/5/2018     Null           Null
2.     Null         1/6/2018       Null
3.     Null         Null           1/7/2018

I used the following query to get the desired results

SELECT id, status,
 CAST( DATEFIELD AS DATE) AS "Timestamp_A",
 CAST(NULL AS DATE) AS "Timestamp_B",
 CAST(NULL AS DATE) AS "Timestamp_C"
FROM table 1
WHERE status='A'

UNION ALL

SELECT id, status,
 CAST( DATEFIELD AS DATE) AS "Timestamp_B",
 CAST(NULL AS DATE) AS "Timestamp_A",
 CAST(NULL AS DATE) AS "Timestamp_C"
FROM table 1
WHERE status='B'

UNION ALL

SELECT id, status,
 CAST( DATEFIELD AS DATE) AS "Timestamp_C",
 CAST(NULL AS DATE) AS "Timestamp_A",
 CAST(NULL AS DATE) AS "Timestamp_B"
FROM table 1
WHERE status='C'

Although each query works individually, when I use UNION ALL only the first query seems to work with respect to datefields i.e only Timestamp_A is populated with the correct values, while Timestamps B and C are all Nulls.

id    Timestamp_A  Timestamp_B    Timestamp_C
1      1/5/2018     Null           Null
2.       Null       Null           Null
3.       Null       Null           Null

Any input or direction on why this is happening?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
data_analyst
  • 27
  • 1
  • 4

2 Answers2

3

The order of your columns is the issue. You have to keep the order the same... But then again you don't really need the unions at all:

SELECT id
    , CASE WHEN DateField = '1/5/2018' THEN DateField END AS TimeStampA
    , CASE WHEN DateField = '1/6/2018' THEN DateField END AS TimeStampB
    , CASE WHEN DateField = '1/7/2018' THEN DateField END AS TimeStampC
FROM t
kjmerf
  • 4,275
  • 3
  • 21
  • 29
2

I believe you want:

SELECT id, status,
       (CASE WHEN status = 'A' THEN datefield END) AS Timestamp_A,
       (CASE WHEN status = 'B' THEN datefield END) AS Timestamp_B,
       (CASE WHEN status = 'C' THEN datefield END) AS Timestamp_C
FROM t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786