我正在尝试在MS SQL 2005中创建一个查询,它将4个日期范围的数据作为结果集中的单独列返回。
现在我的查询看起来像下面的查询。它工作正常,但我想为每个日期范围添加额外的列,因为它当前支持一个日期范围。
这将返回total1,total2,total3和total 4列,而不是像下面的当前查询那样返回单个总列。每个总数代表4个日期范围:
我很确定这可以使用案例陈述来完成,但不是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
答案 0 :(得分:4)
我通常这样做:
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
您可以更改WHEN
部分以制作所需的日期范围。
答案 1 :(得分:0)
使用子查询,即
select sd.vendor, sd.location, sd1.total, sd2.total, sd3.total, sd4.total
from (select distinct vendor, location from saledata) AS sd
LEFT JOIN (
SELECT vendor,location, sum(ExtPrice) as total
FROM [database].[dbo].[saledata]
where processdate between 'startdate1' and 'enddate1'
and location <>''
and vendor <> ''
group by vendor,location with rollup) sd1 on sd1.vendor=sd.vendor and sd1.location=sd.location
LEFT JOIN (
SELECT vendor,location, sum(ExtPrice) as total
FROM [database].[dbo].[saledata]
where processdate between 'startdate2' and 'enddate2'
and location <>''
and vendor <> ''
group by vendor,location with rollup) sd2 on sd2.vendor=sd.vendor and sd2.location=sd.location
LEFT JOIN (
SELECT vendor,location, sum(ExtPrice) as total
FROM [database].[dbo].[saledata]
where processdate between 'startdate3' and 'enddate3'
and location <>''
and vendor <> ''
group by vendor,location with rollup) sd3 on sd3.vendor=sd.vendor and sd3.location=sd.location
LEFT JOIN (
SELECT vendor,location, sum(ExtPrice) as total
FROM [database].[dbo].[saledata]
where processdate between 'startdate4' and 'enddate4'
and location <>''
and vendor <> ''
group by vendor,location with rollup) sd4 on sd4.vendor=sd.vendor and sd4.location=sd.location