删除case语句中的空值

时间:2018-03-20 17:57:06

标签: sql sql-server tsql

我试图将当前星期一与之前的星期一数据一起返回。我想卷起我的空值或0000以返回一个记录。

select 
    da.Customer,
    sum(case 
           when DAteadd(wk, datediff(wk, 0, Getdate()), 1) = d.FullDate           
              then (da.[USD - Balance])
              else 0 
        end) as MondayofCurrentWeek,
    sum(case 
           when DAteadd(wk, datediff(wk, 0, Getdate() - 7), 1) = d.FullDate  
              then (da.[USD - Balance])
              else 0
        end) as PreviousMonday
from 
    Dataset_DemandArchive da 
inner join 
    Dimdate d on d.DateNameUS = da.CREDAT_0
where 
    da.CREDAT_0 in (dateadd(wk, datediff(wk, 0, Getdate()), 1),
                    dateadd(wk, datediff(wk, 0, Getdate() - 7), 1))
group by 
    Customer, FullDate 
order by 
    1

enter image description here

1 个答案:

答案 0 :(得分:0)

为什么不直接使用窗口函数?

select da.*
from (select da.Customer, d.FullDate,
             sum(da.[USD - Balance]) as MondayCurrentWeek
             lag(sum(da.[USD - Balance]), 7) over (partition by da.Customer order by d.FullDate)
      from Dataset_DemandArchive da join
           Dimdate d
           on d.DateNameUS = da.CREDAT_0
      group by Customer, FullDate 
    ) da
where da.CREDAT_0 = dateadd(week, datediff(week, 0, Getdate()), 1)