2016-07-23 51 views
-1

我有一个查询捕获多条件的总和(见下文),但是,我想做同样的事情,但如果可能的话在case语句。总结在sql server中的多个条件

原始查询:

select 
sum(Total Cost) 
from Table 
where date between '7/20/2016' and '7/21/2016' 
and customer = "New Customer" 
and sales like 's%' 

我试图把在一个case语句。

select 
sum(case when total cost is not null then 1 else 
    case when customer = 'New Customer' then 1 else 
    case when sales like 's%' then 1 else 
    end end end 
from table 
where date between '7/20/2016' and '7/21/2016' 

感谢您的帮助

+1

编辑您的问题,并提供样本数据和期望的结果。你的逻辑并不合理。 。 。你似乎想要一个总是返回1的'case'表达式。 –

回答

0

我认为你正在寻找的东西是这样的:

SELECT SUM(CASE WHEN customer = 'New Customer' AND sales LIKE 's%' THEN [Total Cost] END) 
FROM Table 
WHERE [date] BETWEEN '2016-07-20' AND '2016-07-21' 

请注意 - 在你的问题的第二个查询等效于count,不sum。此外,当使用字符串来表示日期时,总是使用yyyy-mm-dd格式,以避免模棱两可 - 在sql server中 - 1/4/2016可能是4月1日,但也可能是1月4日。不过,2016-04-01只能是4月1日。

+0

感谢你对你提供的查询的回应......基础,我没有得到想要的结果......它返回空值 当我运行第一个查询(原始),总费用总计高达80,463 – ZYK

+0

然后请编辑您的问题,以包括示例数据为DDL + DML和期望的结果。 –