显示 0 Not Null With Pivot

Show 0 Not Null With Pivot

为什么我最初的 Select 语句中的 Coalesce() 语句没有用 0 替换 Null

Select * From
(
    Select a.orderstatus As [Stat], Coalesce(Count(b.id), '0') As [Count], b.region
    From orderstatus a
    Left Join saleinfo b
    on b.orderstatus = a.orderstatus
    Group By a.orderstatus, b.region
) one
    pivot ( Max([Count]) For region In ([East], [West], [North], [South]) ) pv

因为您在内部查询中使用它,而问题是记录不存在,因此 PIVOT 在处理内部查询后创建 NULL。如果您的查询 (one) 返回:

Stat    Count   Region
-------------------------
Stat1   0       East
Stat2   2       East
Stat1   5       West

你最终会得到一个像

这样的枢轴Table
Stat    East    West    North   South
---------------------------------------
Stat1   0       5       NULL    NULL
Stat2   2       NULL    NULL    NULL

例如,您得到 NULL for (Stat2, West),因为您的子查询中没有结果,所以 COALESCE 没有帮助。您的解决方法是仅在 PIVOT 本身中使用 COUNT

SELECT  pvt.OrderStatus, pvt.East, pvt.West, pvt.North, pvt.South
FROM    (   SELECT  os.OrderStatus, si.Region, si.ID
            FROM    OrderStatus AS os
                    LEFT JOIN SaleInfo AS si
                        ON si.OrderStatus = b.OrderStatus
        ) AS t
        PIVOT
        (   COUNT(ID)
            FOR Region IN ([East], [West], [North], [South])
        ) AS pvt;

或者把 COALESCE 放在外面 select:

SELECT  pvt.OrderStatus, 
        East = COALESCE(pvt.East, 0), 
        West = COALESCE(pvt.West, 0), 
        North = COALESCE(pvt.North, 0), 
        South = COALESCE(pvt.South, 0)
FROM    (   SELECT  os.OrderStatus, si.Region, [Count] = COUNT(si.ID)
            FROM    OrderStatus AS os
                    LEFT JOIN SaleInfo AS si
                        ON si.OrderStatus = b.OrderStatus
        ) AS t
        PIVOT
        (   MAX([Count])
            FOR Region IN ([East], [West], [North], [South])
        ) AS pvt;

虽然我更喜欢第一个选项。


编辑

示例显示使用 COUNT 时不存在的数据返回 0:

SELECT  pvt.Stat, pvt.East, pvt.West, pvt.North, pvt.South
FROM    (VALUES
            ('Stat1', 'East', 1),
            ('Stat2', 'East', 2),
            ('Stat1', 'West', 3)
        ) t (Stat, Region, ID)
        PIVOT
        (   COUNT(ID)
            FOR Region IN ([East], [West], [North], [South])
        ) AS pvt;