具有多个日期范围的查询/子查询

时间:2017-05-22 16:45:41

标签: sql sql-server-2008 select

我正在尝试找到一种使用子查询检索数据的方法,其中每周性能以及customerid返回的年度性能结果。使用以下语句时,结果为总销售额,而不是客户ID的销售额(每行)。

Select CUSTOMERID, 
  SUM(Amount_Sales), 
  (Select SUM(Amount_Sales), 
   From SalesTable 
   Where SaleDate>='01/01/2017' 
     and SaleDate<='12/31/2017')
From SalesTable
Where SaleDate>='05/22/17' and SaleDate<='05/28/17'
GROUP BY CUSTOMERID

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合在单个聚合中执行此操作:

select customerid,
    sum(amount_sales) as annual_sales,
    sum(case when saledate >= '2017-05-22'
                and saledate <= '2017-04-28' 
        then amount_sales else 0 end) as weekly_sales
from salestable
where saledate >= '2017-01-01'
    and saledate <= '2017-12-31'
group by customerid;