2017-03-08 32 views
1

我有誰購買了多項服務,並具有一批計費的收費客戶的表旁邊:使用count和案例,但只計算occurence一次

| 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費用。理論上說,每個客戶至少應該有一個收費,我試圖確定數據的完整性。

所以我的理想輸出是:

| 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爲每個客戶。

回答

0

希望,我正確理解問題

我想只是group by缺失。

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

如果返回,而不是1 CustAccount可以在其​​上使用不同的:

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 
0

另一個SAMPE查詢: (這是與其他人重複回答)

;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