在sql中创建类似于构造的“数据透视表”

时间:2017-09-14 20:49:22

标签: sql pivot case

这有点令人费解,但我有一个名为dbo.sizeclassreport的表。如果这有点模糊,我道歉。

它有78656行/记录并不是那么大。有三个突出的领域;就业,面积和规模。

下面的示例数据
Area     Employment    sizeclass
000003       4              01
000001       6              02
000013      12              03
000003       2              01
000005      23              04
000001       7              02
000003      11              03

从这里开始,结果就是这样。有9个大小和18个区域。每个区域需要产生9次故障。每个区域都按大小等级进行细分。

Area        Sizeclass     Employment in Size Class    Number of Sites
Total           00                17(6+11)                    3
000003          01                6 (4+2)                     2 
000003          02              NULL or Empty             NULL or Empty
000003          03                    11                      1
......
000003          09              NULL or Empty             NULL or Empty

2 个答案:

答案 0 :(得分:1)

看起来您想要输出中的所有areasizeclass s。如果是,请使用cross join生成结果,然后使用left joingroup by进行计算:

select a.area, sc.sizeclass,
       sum(scr.employment) as employment,
       count(scr.area) as number_of_sizes
from (select distinct area from dbo.sizeclassreport scr) a cross join
     (select distinct sizeclass from dbo.sizeclassreport scr) sc left join
     dbo.sizeclassreport scr
     on a.area = scr.area and sc.sizeclass = scr.sizeclass
group by a.area, sc.sizeclass;

注意:这会为最后一列返回0而不是NULL。这对我来说更有意义。但是,如果您真的需要NULLIF()值,则可以使用NULL

答案 1 :(得分:1)

SELECT 
    [Areas].[Area], 
    [classSizes].[sizeclass],
    SUM([data].[Employment]) AS [Employment in Size Class],
    /*this would be better with your PK */
    CASE COUNT([data].[Employment])
        WHEN 0 THEN NULL
        ELSE COUNT([data].[Employment])
        END  AS [Number of Sites]

/*These rows create your base matix*/
FROM (SELECT DISTINCT 
        [Area] 
    FROM [sizeclassreport]) AS [Areas] 
CROSS JOIN (SELECT DISTINCT 
                [sizeclass] 
            FROM [sizeclassreport]) AS [classSizes] 

/* this is where you select your data*/
LEFT OUTER JOIN [sizeclassreport] [data]
     ON [Areas].[Area] = [data].[Area] 
        AND [classSizes].[sizeclass] = [data].[sizeclass]
GROUP BY
    [areas].[Area], 
    [classSizes].[sizeclass]
ORDER BY
    [areas].[Area], 
    [classSizes].[sizeclass]