在 select 语句中使用 Case

using Case in select statement

我有这样一种情况,我要从 table 中总结几列并将结果插入到另一个 table 中。这是按县和区分组的。其中一列还从该地区的一家零售商那里获得了最小的总销售额。我遇到的问题是,总销售额可能低于零。我只想将大于零的最小值写入该列。

declare @WeekEnd datetime
set @WeekEnd = (select top(1) date from sales order by date desc)
select date
,county
,district
,sum(prod1) 
,sum(prod2) 
,sum(prod3) 
,sum(prod4) 
,sum(prod1+prod2+prod3+prod4) --Total Sales
,Case when min(prod1+prod2+prod3+prod4) > 0 then min(prod1+prod2+prod3+prod4)
--this works well except for when a total is less than zero, then it is null. I want to avoid the null and have it write the smallest value greater than zero. 
end
from sales 
where date = @WeekEnd
group by date,county,district
order by county, district

没试过,但我想这行得通:

min(Case when prod1+prod2+prod3+prod4 <= 0 
    then null else prod1+prod2+prod3+prod4 end)

如果我没看错您的问题,您需要使用子查询获取 MIN TotalSales:

declare @WeekEnd datetime
set @WeekEnd = (select top(1) date from sales order by date desc)
select date
,county
,district
,sum(prod1) 
,sum(prod2) 
,sum(prod3) 
,sum(prod4) 
,sum(prod1+prod2+prod3+prod4) --Total Sales
,(SELECT min(prod1+prod2+prod3+prod4)
  FROM sales s2
  WHERE s1.date=s2.date
  AND s1.county=s2.county
  AND s1.district=s2.district
  AND (prod1+prod2+prod3+prod4)>0
)
from sales s1
where date = @WeekEnd
group by date,county,district
order by county, district