具有复杂Sum条件挑战的案例陈述

时间:2012-06-19 10:48:24

标签: sql sql-server

需要SQL神的帮助

表1 - DistinctQuotes

此表包含有关引号的信息。

所以我们有

+-------+-----------+--------------+------+-----------------+
|REGION | SubRegion | Market Route | Type | Quotations Count|
+-------+-----------+--------------+------+-----------------+
|EMEA   | Germany   | Direct       | DS1  | 12              |
|EMEA   | Germany   | NonDirect    | DS1  | 22              |
|EMEA   | Germany   | Direct       | DS1  | 2               |
|EMEA   | Germany   | NOnDirect    | DS1  | 4               |
|EMEA   | France    | Direct       | DS1  | 4               |
|EMEA   | UK        | Direct       | DS1  | 4               |
+-------+-----------+--------------+------+-----------------+

所以我想显示来自DS1类型和市场路线是直接的每个子区域的计数。

现在,下面的查询错误,因为引号计数来自匹配行的报价计数总和,而不是来自匹配行的计数 [市场路线] ='直接'和[类型] ='DS1'。

任何人都可以帮我改变下面的查询来捕捉我需要的东西吗?

SELECT        
 [Region]  ,[SubRegion]      
   ,SUM (CASE WHEN [Market Route] = 'Direct' AND [Type] = 'DS1' 
   THEN 1 ELSE 0 END)               as [Count of Direct quotes from  DS1] 
FROM [dbo].[V_DistinctQuotes]
  GROUP by  [SubRegion],[Region] 

3 个答案:

答案 0 :(得分:3)

只需将THEN 1 ELSE 0更改为THEN [Quotations Count] ELSE 0

答案 1 :(得分:1)

这会有用吗?

SELECT
[Region] ,[SubRegion] ,Count(*) as [Count of Direct quotes from DS1] 
FROM  [dbo].[V_DistinctQuotes] 
WHERE [Market Route] = 'Direct' AND [Type] = 'DS1'
GROUP by [SubRegion],[Region] 

答案 2 :(得分:1)

我不确定我是否正确理解您的问题,但如果您想要市场路线为“直接”且类型为“DS1”的报价计数(实际上是[报价计数]字段的总和),请执行以下操作:

SELECT        
 [SubRegion],sum([Quotations Count])
 from
[dbo].[V_DistinctQuotes]
where
MarketRoute='Direct' and [Type] ='DS1'

group by [SubRegion]

产生:

SubRegion   (No column name)
France  4
Germany 14
UK      4