SQL Server: Splitting a Column into Multiple Columns with a Concatenated Table
I have 3 tables A, B, C
Table A
sID sName
1 Apple
2 Banana
3 Cherry
Table B
PointID PointName sID
1 seed 1
2 seed 2
3 stem 1
4 stem 2
5 stem 3
6 root 2
7 leave 1
Table C
PointID Time pointValue
1 2013-03-15 12:00:00 23.0
2 2013-03-15 12:00:00 24.0
5 2013-03-15 12:00:00 25.0
1 2013-03-15 13:00:00 26.0
2 2013-03-15 13:00:00 27.0
6 2013-03-15 13:00:00 28.0
2 2013-03-16 13:00:00 29.0
6 2013-03-16 13:00:00 30.0
7 2013-03-15 13:00:00 31.0
I need the result to be like this (just show the whole result filtered by time):
Time sName seed stem root
2013-03-15 12:00:00 Apple 23.0 NULL NULL
2013-03-15 12:00:00 Banana 24.0 NULL NULL
2013-03-15 12:00:00 Cherry NULL 25.0 NULL
2013-03-15 13:00:00 Apple 26.0 NULL NULL
2013-03-15 13:00:00 Banana 27.0 NULL 28.0
I came up with a solution using multiple joins, however my results show the time and name s named seed, stem, root as NULL because pointName is not required.
SELECT HEADER.TIME
,HEADER.sName
,SD.seed
,STM.stem
,RT.root
FROM (
SELECT C.TIME
,A.sName
FROM B
INNER JOIN C ON B.PointID = C.PointID
INNER JOIN A ON B.sID = A.sID
) HEADER
FULL JOIN (
SELECT C.TIME
,A.sName
FROM B
INNER JOIN C ON B.PointID = C.PointID
INNER JOIN A ON B.sID = A.sID
WHERE B.PointName = "seed"
) SD ON HEADER.TIME = SD.TIME
AND HEADER.sName = SD.sName
FULL JOIN (
SELECT C.TIME
,A.sName
FROM B
INNER JOIN C ON B.PointID = C.PointID
INNER JOIN A ON B.sID = A.sID
WHERE B.PointName = "stem"
) STM ON HEADER.TIME = STM.TIME
AND HEADER.sName = STM.sName
FULL JOIN (
SELECT C.TIME
,A.sName
FROM B
INNER JOIN C ON B.PointID = C.PointID
INNER JOIN A ON B.sID = A.sID
WHERE B.PointName = "root"
) RT ON HEADER.TIME = RT.TIME
AND HEADER.sName = RT.sName
WHERE (HEADER.TIME > '2013-03-15 11:00:00')
AND (HEADER.TIME < '2013-03-16 20:00:00')
I tried adding an OR clause in the outermost where argument to check if one of the three columns is not null. But got no return results instead
WHERE (HEADER.Time > '2013-03-15 11:00:00') AND (HEADER.Time < '2013-03-16 20:00:00')
AND (SD.seed <> NULL OR STM.stem <> NULL OR RT.root <> NULL)
Would it be great that NULL choices would be allowed or comment if there is a better solution? Since I'm not sure if my current method will be good at implementing with even more columns to be
+3
source to share
1 answer
I believe you will need PIVOT for this , given the need to project row data into columns:
SELECT Date, sName, [seed], [stem], [root], [leave]
FROM
(
SELECT DATE, [PointName], [sName], PointValue
FROM C
LEFT JOIN B ON C.PointID = B.POINTID
LEFT JOIN A ON B.[sID] = A.[sID]
) p
PIVOT
(
SUM(PointValue)
FOR [PointName] IN ( [seed], [stem], [root], [leave])
) y;
+4
source to share