根据日期创建列值

时间:2018-08-08 21:20:00

标签: sql-server sql-server-2012 datetime-format

我有一个包含以下各列的视图

requested_delivery (DateTime field but time part is always 00:00:00)
product
qty

我想为TodayToday+1Today+2等创建列,如果qty字段匹配则在字段中包含requested_delivery或0如果没有

视图中的列应为

requested_delivery, product, qty, Today, Today+1, Today+2

1 个答案:

答案 0 :(得分:0)

这听起来像您想要条件聚合:

select
   requested_delivery
   ,product
   ,Today = sum(case cast(requested_delivery as date) = cast(getdate() as date) then qty end)
   ,Today+1 = sum(case cast(requested_delivery as date) = dateadd(day,1,cast(getdate() as date)) then qty end)
   ,Today+2 = sum(case cast(requested_delivery as date) = dateadd(day,2,cast(getdate() as date)) then qty end)
from yourView

如果目标是在“今日+ 1”字段中显示今天和明天的所有项目,即滚动号或累计值,则可以使用以下方法:

select
   requested_delivery
   ,product
   ,Today = sum(case cast(requested_delivery as date) = cast(getdate() as date) then qty end)
   ,Today+1 = sum(case cast(requested_delivery as date) between cast(getdate() as date) and dateadd(day,1,cast(getdate() as date)) then qty end)
   ,Today+2 = sum(case cast(requested_delivery as date) between between cast(getdate() as date) and dateadd(day,2,cast(getdate() as date)) then qty end)
from yourView