为不存在的条目创建值

时间:2015-11-06 09:44:55

标签: sql sql-server sql-server-2008

我正在努力解决以下问题(SQL Server)。

我有一张看起来像这样的表

DATE    Type  max_orders   ID
-------------------------------
null    1       600       10000
null    2       600       10001
null    3       600       10002
4.11    1       500       10003
4.11    2       300       10004
4.11    3       250       10005
5.11    1       550       10006
5.11    2       500       10007
5.11    3       400       10008

我想要做的是写一个查询,它会告诉我今天,明天和明天之后的max_orders数量是多少。

我们假设今天是3.11并且我的表中没有该日期的条目,这意味着当天的max_orders应该与日期为null的位置相同(在这种情况下为600)

像这样:

Type  max_orders_Today max_orders_tmrw  max_orders_dayafter
------------------------------------------------------------
    1       600              500                550
    2       600              300                500
    3       600              250                400

我的错误查询如下:

with cap as 
(
    select 
        date, type, max_orders, ID 
    from 
        mytable
    where 
        type in ('1','2','3') 
)
select 
    d.type,
    case 
       when d.Date = GETDATE() then d.max_orders 
       when d.Date IS NULL then cap.max_orders 
    end as today,
    case 
       when d.Date = DATEADD(day, +1, GETDATE()) then d.max_orders 
       when d.Date IS NULL then cap.max_orders 
    end as tomorrow,
    case 
       when d.Date = DATEADD(day, +2, GETDATE()) then d.max_orders 
       when d.Date IS NULL then cap.max_orders 
    end as day_after
from 
    mytable AS d
left join 
    cap on d.Id = cap.Id

它随处返回一堆空值。我很感激能得到的任何帮助!

2 个答案:

答案 0 :(得分:1)

首先,您要选择三种类型,1,2和3,无论数据是否可用。首先,为这些创建记录。然后加入默认值。最后在SELECT子句中的子查询中选择日期特定值。

select 
  type,
  coalesce
  (
    (
      select max_orders from mytable 
      where type = types.type and date = getdate()
    )
  ), defaults.max_orders) as max_orders_today,
  coalesce
  (
    (
      select max_orders from mytable 
      where type = types.type and date = dateadd(day, 1, getdate()) 
    )
  ), defaults.max_orders) as max_orders_tmrw,
  coalesce
  (
    (
      select max_orders from mytable 
      where type = types.type and date = dateadd(day, 2, getdate()) 
    )
  ), defaults.max_orders) as max_orders_dayafter
from
(
  select 1 as type union all 
  select 2 as type union all 
  select 3 as type 
) as types
left join
(
  select type, max_orders 
  from mytable 
  where date is null
) as defaults on defaults.type = types.type
order by types.type;

答案 1 :(得分:0)

在选择查询中尝试使用select和having选项。 并按日期制作小组并按日期过滤<三天

选择日期,类型,最大值(max_orders),来自mytable的id,其中date不是null group by(date)having(data< = DATEADD(day,+ 2,GETDATE()))