合并查询以显示一组结果

时间:2018-11-08 14:03:12

标签: sql sql-server tsql

我有两个独立的查询,需要根据日期值进行匹配和组合。

select convert(varchar,Delivery_Date,101) as 'Date',
sum(case when billing_group = '3' and delivery_date >= dateadd(day,datediff(day, 0, GetDate()) - 30, 0) then 1 else 0 end) as 'OR to WA'
    from orders 
    where delivery_Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and billing_group in ('3') 
    group by delivery_date
    order by date desc


select convert(varchar,Origin_Date,101) as 'Date',
sum(case when billing_group = '4' and origin_date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0)then 1 else 0 end) as 'WA to OR'
        from orders 
        where origin_Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and billing_group in ('4') 
        group by origin_Date
        order by date desc

enter image description here

请注意,我在第一个查询中使用不同的日期值(delivery_date),而在第二个查询中使用了不同的日期值(origin_date)

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我认为您只需要条件聚合,但是您的查询还提供了其他改进空间:

select convert(varchar(255), v.thedate, 101) as [Date],
       sum(case when o.billing_group = 3 then 1 else 0 end) as [OR to WA],
       sum(case when o.billing_group = 4 then 1 else 0 end) as [WA to OR]
from orders o cross apply
     (values (case when o.billing_group = 3 then delivery_date else o.origin_date end)
     ) v(the_date)
where v.thedate >= dateadd(day, -30, cast(getdate() as date)) and
      o.billing_group in (3, 4) 
group by convert(varchar(255), v.thedate, 101)
order by v.thedate desc

注意:

  • 切勿使用没有长度参数的varchar()。长度因上下文而异,可能无法满足您的预期。
  • 我猜billing_group是一个数字。如果是这样,请勿使用单引号。如果我错了,请使用使用单引号。
  • 我无法确定delivery_date的数据类型是什么。通过完整的表达式而不是仅通过列进行聚合是更安全的。
  • 请勿对列别名使用单引号。仅对字符串和日期常量使用单引号。
  • 没有理由使用在0上增加天数的“技巧”来删除时间部分。相反,只需转换为date
  • delivery_date上的条件不必同时出现在case表达式和where子句中。

答案 1 :(得分:0)

尝试使用UNION并添加缺少的列 然后进行分组和订购

select * from (
 convert(varchar,Delivery_Date,101) as 'Date',
sum(case when billing_group = '3' and delivery_date >= dateadd(day,datediff(day, 0, GetDate()) - 30, 0) then 1 else 0 end) as 'OR to WA',
0 as 'WA to OR'
    from orders 
    where delivery_Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and billing_group in ('3') 
   -- group by delivery_date
   --- order by date desc

UNION

select convert(varchar,Origin_Date,101) as 'Date',
0 as 'OR to WA'
sum(case when billing_group = '4' and origin_date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0)then 1 else 0 end) as 'WA to OR'
        from orders 
        where origin_Date >= dateadd(day, datediff(day, 0, GetDate()) - 30, 0) and billing_group in ('4') 
        --group by origin_Date
        --order by date desc

        ) group by [Date] 
        order by [Date] desc