如何在使用SQL Server 2008的情况下使用多个CASE?

我想要做的是使用不止一个CASE WHEN条件相同的列。

这是我查询的代码:

SELECT Url='', p.ArtNo, p.[Description], p.Specification, CASE WHEN 1 = 1 or 1 = 1 THEN 1 ELSE 0 END as Qty, p.NetPrice, [Status] = 0 FROM Product p (NOLOCK) 

但是,我想要做的是多用一个WHEN为同一列“数量”。

如下面的代码所示:

 IF // CODE ELSE IF // CODE ELSE IF // CODE ELSE // CODE 

有两种格式的expression式 。 你可以用很多时候做CASE ;

 CASE WHEN Col1 = 1 OR Col3 = 1 THEN 1 WHEN Col1 = 2 THEN 2 ... ELSE 0 END as Qty 

或者一个简单的CASEexpression式

 CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END 

CASE CASE为;

 CASE WHEN Col1 < 2 THEN CASE Col2 WHEN 'X' THEN 10 ELSE 11 END WHEN Col1 = 2 THEN 2 ... ELSE 0 END as Qty 

只要用这个,上课的时候就得多用点。

 SELECT Url='', p.ArtNo, p.[Description], p.Specification, CASE WHEN 1 = 1 or 1 = 1 THEN 1 WHEN 2 = 2 THEN 2 WHEN 3 = 3 THEN 3 ELSE 0 END as Qty, p.NetPrice, [Status] = 0 FROM Product p (NOLOCK) 
 case when a.REASONID in ('02','03','04','05','06') then case b.CALSOC when '1' then 'yes' when '2' then 'no' else 'no' end else 'no' end 
  case when first_condition then first_condition_result_true else case when second_condition then second_condition_result_true else second_condition_result_false end end end as qty 

我有一个类似的,但它是在处理date。 查询显示上个月的所有项目,直到1月份才能正常工作。为了正确工作,需要添加年份和月份variables

 declare @yr int declare @mth int set @yr=(select case when month(getdate())=1 then YEAR(getdate())-1 else YEAR(getdate())end) set @mth=(select case when month(getdate())=1 then month(getdate())+11 else month(getdate())end) 

现在我只是添加variables的条件:…

 (year(CreationTime)=@yr and MONTH(creationtime)=@mth) 

结合所有条件

 select a.* from tbl_Company a where a.Company_ID NOT IN (1,2) AND ( (0 = CASE WHEN (@Fromdate = '' or @Todate='') THEN 0 ELSE 1 END ) -- if 0=0 true , if 0=1 fails (filter only when the fromdate and todate is present) OR (a.Created_Date between @Fromdate and @Todate ) ) 

这可以是对单个语句执行不同testing的有效方法

 select case colour_txt when 'red' then 5 when 'green' then 4 when 'orange' then 3 else 0 end as Pass_Flag 

这只适用于平等的比较!