-1

这些是查询

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())

是否可以组合所有这些查询以获得输出为

周销售月销售年销售

有任何想法吗?

4

2 回答 2

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()计算列中非空值的总数。

于 2013-09-25T13:15:41.913 回答
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') 
于 2013-09-25T13:15:43.863 回答