SQL Server:使用连接表将列拆分为多个列

时间:2014-12-20 19:31:57

标签: sql sql-server

我有3张表A,B,C

表A

sID sName
1   Apple
2   Banana
3   Cherry

表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

表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

我需要输出像这样(只显示按时间过滤的所有结果):

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

我已经提出了一个使用多个连接的解决方案,但是我的结果确实显示时间和sName,种子,词干,根目录为NULL,因为pointName"离开"不需要。

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')

我试图在最外层的where子句中添加OR子句,以检查3列中的一列是否为空。但是没有得到回报结果

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)

解决NULL选择会很棒,或者如果有更好的解决方案则会发表评论?因为我不确定我的当前方法是否适用于具有更多多列的实现

1 个答案:

答案 0 :(得分:4)

我认为你需要一个PIVOT,因为需要将行数据投射到列中:

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;

SqlFiddle