2017-11-28 19 views
0
Id, CustomerId, IsKnownCustomer,phonemacaddress 

1, NULL   0    00:9a:34:cf:a4 
2, 004024  1    00:6f:64:cf:a0:93 
3, 004024  1    00:6f:64:cf:a0:93 
4, 004003  1    2c:0e:3d:15:12:43 
6, NULL   0    2c:0e:3d:15:125 
7, 004003  1    34:f3:9a:ee:53:a9 
8, 004023  1    38:0B:40:DC:BA:3A 
9, NULL   0    4c:66:41:11:26:16 

これは表であり、すべての顧客、未知の顧客および既知の顧客に必要です。すべての(未知の既知の)未知の既知の顧客のためのSQLクエリ

出力:phonemacaddressによってレコードを一意に見つけます。

count Customer, customer type 
7     all 
3     unknown customer 
4     known customer 
+0

GROUP BYこの文字列で検索してください。条件付き集計を行うには、case式を使用します。 – jarlh

答えて

2

これは使用できます。

SELECT COUNT(DISTINCT phonemacaddress) [count Customer] , 
    CASE 
     WHEN GROUPING(IsKnownCustomer) = 1 THEN 'all' 
     WHEN IsKnownCustomer = 1 THEN 'known customer' 
     WHEN IsKnownCustomer = 0 THEN 'unknown customer' END [customer type] 
FROM @CustomerTable 
GROUP BY IsKnownCustomer WITH ROLLUP 
ORDER BY GROUPING(IsKnownCustomer) DESC, IsKnownCustomer 

結果:

count Customer customer type 
-------------- ---------------- 
7    all 
3    unknown customer 
4    known customer 
+0

これはphonemacaddressに基づいている必要があります。出力は期待される出力とは異なります –

0

select count(Id), 'All' as customer_type from customers 
union 
select count(Id), 'Unknown' as customer_type from customers 
WHERE isKnownCustomer =0 
union 
select count(Id), 'known' as customer_type from customers 
WHERE isKnownCustomer =1; 

http://sqlfiddle.com/#!9/3e7616/15

関連する問題