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

sql pulling data in in certain rows but not others

table 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 种小时类型,对于给定的文件密钥

,每种类型可能存在也可能不存在

将生成第一行的查询与生成其他三行的查询联合。

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

尝试以下操作:

 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

在场景 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