sql在某些行中提取数据但不在其他行中

时间:2018-05-17 14:01:09

标签: sql sql-server-2008-r2

表1看起来像这样:

filekey  hourstype   hours
 123        1          40
 123        2           5
 123        3           6
 123        4           7
 123        5           8

所需的输出应如下所示:

filekey   hours1    hours2    otherhourstype otherhourstotal
 123        40        5          ''             ''
 123        ''        ''         3              6
 123        ''        ''         4              7
 123        ''        ''         5              8

小时1和小时2占据同一行,所有其他小时占据自己的行

还有另一种可行的格式:

filekey   hours1    hours2    difhrstype difhrstotal  difhourstype difhrstotal
 123        40        5          3             6         4              7
在这种情况下,

以最低小时类型开始,然后通过列而不是每个文件键一行的总延伸。我不知道如何让这个发生。特别是因为对于给定的文件密钥可能存在或可能不存在最多8个小时类型

3 个答案:

答案 0 :(得分:0)

UNION一个查询,它将在将产生其他三行的查询上生成第一行。

为每个查询中未使用的列硬编码NULL(或空格或任何你想要的内容)。

答案 1 :(得分:0)

尝试以下方法:

 select 
    pivottable.filekey,
    [1] as hours1,
    [2] as hours2,
    [3] as hours3,
    [4] as hours4,
    [5] as hours5,
    [6] as hours6,
    [7] as hours7,
    [8] as hours8
 from table1
 PIVOT (
 sum(hours)
 FOR hourstype IN ([1],[2],[3],[4],[5],[6],[7],[8]) 
 ) as pivottable

答案 2 :(得分:0)

尝试使用方案1:

CREATE TABLE #TMP(filekey INT, hourstype INT, [hours] INT)

INSERT INTO #TMP VALUES
(123,1,40)
,(123,2,5)
,(123,3,6)
,(123,4,7)
,(123,5,8)

SELECT
    T.filekey
    ,SUM(CASE WHEN hourstype = 1 THEN [hours] ELSE 0 END) AS hours1
    ,SUM(CASE WHEN hourstype = 2 THEN [hours] ELSE 0 END) AS hours2
    ,CASE WHEN hourstype > 2 THEN [hourstype] ELSE 0 END AS otherhourstype
    ,CASE WHEN hourstype > 2 THEN [hours] ELSE 0 END AS otherhourstotal
FROM
    #TMP T
GROUP BY
    T.filekey
    ,CASE WHEN hourstype > 2 THEN [hourstype] ELSE 0 END 
    ,CASE WHEN hourstype > 2 THEN [hours] ELSE 0 END