Sql Sql Pivot 和 Sql 情况下的 ISNULL 条件

Sql ISNULL condition in Sql Pivot and Sql case

我在 SO 和其他地方搜索了很多解决方案,但不太明白如何为我的问题编写查询。

无论如何,我的查询如下所示

SELECT * FROM
(
    SELECT Id, Date, Name, Amount,
    CASE 
        WHEN DATEDIFF(DAY,Date,GETDATE()) <=0 
        THEN 'Current'
        WHEN DATEDIFF(DAY,Date,GETDATE()) <30
        THEN 'Due30'
        WHEN DATEDIFF(DAY,Date,GETDATE()) <60
        THEN 'Due60'
        ELSE 'Due90'
    END AS     [Age] 
    FROM Statement 
    WHERE (Amount <> 0)

) AS S
PIVOT  
(
    SUM(Amount)
    FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P

结果是这样的

  Id   Date       Name    Current     Due30     Due60    Due90
 ----------- ---------- --------------------------------------------
  1   2016-04-03  Alan     NULL       NULL      NULL     110.00
  2   2016-05-02   TC      NULL       NULL      30.00    NULL

我应该在哪里插入 IsNull 条件才能删除结果中的 null 并在那里添加一个零。

我尝试在数据透视表查询中插入 IsNull,但我们都知道这不起作用

SELECT Id
     , [Date]
     , Name
     , [Current] = SUM(CASE WHEN val <= 0  THEN Amount ELSE 0 END)
     , Due30 = SUM(CASE WHEN val < 30 THEN Amount ELSE 0 END)
     , Due60 = SUM(CASE WHEN val < 60  THEN Amount ELSE 0 END)
     , Due90 = SUM(CASE WHEN val >= 60  THEN Amount ELSE 0 END)
FROM dbo.[Statement] t
CROSS APPLY (
    SELECT val = DATEDIFF(DAY, [Date], GETDATE())
) s
WHERE Amount <> 0
GROUP BY Id, [Date], Name

你必须在最后的 SELECT 中重复添加它,当你用列替换 SELECT *(它应该只存在于临时查询或 EXISTS 测试中)名单:

SELECT
  Id,
  Date,
  Name,
  COALESCE([Current],0) as [Current],
  COALESCE(Due30,0) as Due30,
  COALESCE(Due60,0) as Due60,
  COALESCE(Due90,0) as Due90
FROM
(
    SELECT Id, Date, Name, Amount,
    CASE 
        WHEN DATEDIFF(DAY,Date,GETDATE()) <=0 
        THEN 'Current'
        WHEN DATEDIFF(DAY,Date,GETDATE()) <30
        THEN 'Due30'
        WHEN DATEDIFF(DAY,Date,GETDATE()) <60
        THEN 'Due60'
        ELSE 'Due90'
    END AS     [Age] 
    FROM Statement 
    WHERE (Amount <> 0)

) AS S
PIVOT  
(
    SUM(Amount)
    FOR[Age] IN ([Current],[Due30],[Due60],[Due90])
) P

我还使用了 COALESCE,因为它通常是首选选项(ANSI 标准,扩展到两个以上的参数,应用正常的类型优先规则)而不是 ISNULL