使用Count和Case但只计算一次出现次数

时间:2017-03-08 18:22:34

标签: sql sql-server

我有一张顾客表,他们已经购买了许多服务,并且旁边有许多可计费的费用:

| CustAccount | Service  | Charge  | Value  |
|-------------|----------|---------|--------|
| M12345      | ABC123   | SE      | 102.10 |
| M12345      | ABC123   | SE      | 5.36   |
| M12345      | ABC123   | SE      | 250.36 |
| M12345      | ABC123   | OS      | 150.99 |
| M18970      | ABC123   | SE      | 56.35  |
| M18970      | ABC123   | OS      | 9.99   |
| M18970      | ABC123   | SV      | 77.77  |
| M72350      | ABC123   | OS      | 9.99   |
| M72350      | ABC123   | AB      | 9.99   |

我想要做的是运行一个查询,该查询计算唯一客户的数量,并确定其中有多少客户收取SE费用。理论上说,每个客户都应至少收取SE费用,我正在尝试确定数据的完整性。

所以我理想的输出是:

| Service | Customers_count | SE_charges |
|---------|-----------------|------------|
| ABC123  | 3               | 2          |

到目前为止,我的查询是:

SELECT Service, COUNT (DISTINCT CustAccount) AS Customers_count,
    COUNT (CASE WHEN Charge = 'SE' THEN 1 ELSE NULL END) AS SE_charges
FROM MyTable

但是,似乎每个客户都会计算重复的SE值,而我无法确定如何为每位客户计算1 SE

3 个答案:

答案 0 :(得分:3)

如果您返回CustAccount而不是1,则可以使用distinct:

SELECT 
    Service
    , COUNT (DISTINCT CustAccount) AS Customers_count
    , COUNT (DISTINCT CASE WHEN Charge = 'SE' THEN CustAccount ELSE NULL END) AS SE_charges
FROM MyTable
GROUP BY Service

答案 1 :(得分:0)

希望,我正确地理解了问题

我认为只是缺少分组。

if(scores[i] % 2 ==0) {//← i here
        newScores[j] = scores[i];//← j here

答案 2 :(得分:0)

另一个样本查询: (这是与其他人的重复答案)

 ;WITH tb(CustAccount ,Service ,Charge ,Value)AS(
    SELECT 'M12345','ABC123','SE ',102.10  UNION
    SELECT 'M12345','ABC123','SE ',5.36   UNION
    SELECT 'M12345','ABC123','SE ',250.36  UNION
    SELECT 'M12345','ABC123',' OS ',150.99  UNION
    SELECT 'M18970','ABC123','SE ',56.35   UNION
    SELECT 'M18970','ABC123','OS ', 9.99    UNION
    SELECT 'M18970','ABC123',' SV ',77.77   UNION
    SELECT 'M72350','ABC123','OS ', 9.99    UNION
    SELECT 'M72350','ABC123','AB  ',9.99   
    ) 
    SELECT Service,COUNT(DISTINCT tb.CustAccount) AS Customers_count
                  ,COUNT(DISTINCT CASE WHEN tb.Charge='SE' THEN tb.CustAccount ELSE NULL END )SE_charges
                  --,COUNT(DISTINCT CASE WHEN tb.Charge='SE' THEN tb.CustAccount+tb.Charge ELSE NULL END )SE_charges
     FROM tb
    GROUP BY tb.Service
Service Customers_count SE_charges
------- --------------- -----------
ABC123  3               2