我正在尝试在MS SQL 2005中创建查询,该查询将返回4个日期范围的数据作为结果集中的单独列。
现在,我的查询看起来像下面的查询。它工作正常,但是我想为每个日期范围添加其他列,因为它当前支持一个日期范围。
然后,这将返回total1,total2,total3和total 4列,而不是像下面的当前查询那样返回单个total列。每个总计代表4个日期范围:
我相当确定这可以使用case语句来完成,但不是100%。
任何帮助将不胜感激。
SELECT
vendor,location,
sum(ExtPrice) as total
FROM [database].[dbo].[saledata]
where processdate between '2010-11-03' and '2010-12-14'
and location <>''
and vendor <> ''
group by vendor,location with rollup
Run Code Online (Sandbox Code Playgroud)
我通常这样做:
SELECT
vendor,location,
sum(CASE WHEN processdate BETWEEN @date1start AND @date1end THEN xtPrice ELSE 0 END) as total,
sum(CASE WHEN processdate BETWEEN @date2start AND @date2end THEN xtPrice ELSE 0 END) as total2,
sum(CASE WHEN processdate BETWEEN @date3start AND @date3end THEN xtPrice ELSE 0 END) as total3,
sum(CASE WHEN processdate BETWEEN @date4start AND @date4end THEN xtPrice ELSE 0 END) as total4
FROM [database].[dbo].[saledata]
and location <>''
and vendor <> ''
group by vendor,location with rollup
Run Code Online (Sandbox Code Playgroud)
您可以更改该WHEN部分以设置所需的日期范围。