这些是查询
select count(sales) as weeksales from salesdairy where propertytype in ('item1') and DATEPART( wk, time)=DATEPART( wk,getdate())
select count(sales) as monthsales from salesdairy where propertytype in ('item1') and MONTH(time) = MONTH(getdate())
select count(sales) as yearsales from salesdairy where propertytype in ('item1') and YEAR(time) = YEAR(getdate())
是否可以将所有这些查询组合起来以获得输出
weekales monthsales yearsales
有什么想法吗?
答案 0 :(得分:2)
SELECT COUNT(CASE WHEN DATEPART(wk, time) = DATEPART(wk, getdate()) THEN SALES ELSE NULL END) weeksales,
COUNT(CASE WHEN MONTH(time) = MONTH(getdate()) THEN SALES ELSE NULL END) monthsales,
COUNT(CASE WHEN YEAR(time) = YEAR(getdate()) THEN SALES ELSE NULL END) yearsales
FROM salesdairy
WHERE propertytype in ('item1')
但我认为您要使用SUM()
而不是COUNT()
,因为SUM()
计算列的总值,而COUNT()
计算非空值的总数在专栏中。
答案 1 :(得分:2)
select sum(case when DATEPART( wk, time) = DATEPART( wk,getdate())
then sales
else 0
end) as weeksales,
sum(case when MONTH(time) = MONTH(getdate())
then sales
else 0
end) as monthsales,
sum(case when YEAR(time) = YEAR(getdate())
then sales
else 0
end) as yearsales
from salesdairy
where propertytype in ('item1')