在Sql Pivot和Sql案例中的Sql ISNULL条件

时间:2016-06-06 07:24:54

标签: sql sql-server pivot case isnull

我在搜索引擎优化和其他地方搜索了很多解决方案但是我不太了解如何为我的问题编写查询。

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

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,但我们都知道这不适用

2 个答案:

答案 0 :(得分:3)

当您使用列列表替换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

答案 1 :(得分:0)

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