忽略聚合中的空值

时间:2014-10-21 14:19:24

标签: sql-server

我有表区域:

Region Typee      Cnt
1        NEW      1
1        LEAVE    5
1        TOTAL    250
2        NEW      2
2        TOTAL    330
2        LEAVE    10

我希望制作一个如下所示的表格:

Region New Leave Total
1       1    5    250
2       2    10   330

我试过这个:

insert into     DP_CfCustCnt3             select Region,    
  case when Typee = 'NEW' then (select Cnt where typee = 'NEW') end as New,
 case when Typee = 'LEAVE' then (select Cnt where typee = 'LEAVE') end as Leave, 
 case when Typee = 'TOTAL' then (select Cnt where typee ='TOTAL') end as Total
 from Regions

但它给我的表格如下:

Region New Leave Total
1       1    NULL  NULL
1       NULL   5    NULL
1       NULL   NULL 250

感谢您的任何建议。

3 个答案:

答案 0 :(得分:1)

您所描述的是PIVOT功能:

INSERT INTO DP_CfCustCnt3
    SELECT  pvt.Region,
            pvt.New,
            pvt.Leave,
            pvt.Total
    FROM    Regions r
    PIVOT   (
                SUM(Cnt) FOR Typee IN ([NEW],[LEAVE],[TOTAL])
            ) pvt

答案 1 :(得分:1)

您可以在SQL上进行透视或扩展:

insert into     DP_CfCustCnt3
SELECT Region,
        SUM(New) New,
        SUM(Leave) Leave,
        SUM(Total) Total
FROM (
SELECT  Region,
        CASE Typee WHEN 'NEW' THEN Cnt ELSE 0 END AS New,
        CASE Typee WHEN 'LEAVE' THEN Cnt ELSE 0 END AS Leave,
        CASE Typee WHEN 'TOTAL' THEN Cnt ELSE 0 END AS Total

FROM test) data
GROUP BY Region

答案 2 :(得分:0)

select
    REGION,
    SUM(CASE WHEN [TYPEE] = 'NEW' THEN CNT ELSE 0 END) [NEW],
    SUM(CASE WHEN [TYPEE] = 'LEAVE' THEN CNT ELSE 0 END) [LEAVE],
    SUM(CASE WHEN [TYPEE] = 'TOTAL' THEN CNT ELSE 0 END) [TOTAL]
FROM REGIONS
GROUP BY
    REGION