在select语句中使用Case

时间:2016-01-25 19:14:05

标签: sql-server tsql sql-server-2005

我遇到的情况是我从表中汇总了几列并将结果插入到另一个表中。这是按县和地区分组的。其中一个专栏也是该地区零售商的最小总销售额。我遇到的问题是可能会有一些总销售额低于零。我只想将大于零的最小值写入该列。

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

2 个答案:

答案 0 :(得分:1)

如果我正确地阅读您的问题,您需要使用子查询获取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

答案 1 :(得分:0)

Haven没试过,但我认为这很有效:

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