2017-06-12 6 views
0

私はこのテーブルをmysqlに持っています。MySQLユニークアイテム数クエリ

CustomerName CustomerGroup hasPurchase 
Jerry  A    CAR 
Jerry  A    TOY 
Jerry  A    CAR 
Springer  B    DRINK 
Springer  B    CAR 
Springer  B    CAR 
Springer  B    DRINK 

マイ期待される結果:

CustomerName CustomerGroup totalPurchase uniquePurchase 
Jerry  A    3    2 
Springer  B    4    2 

totalPurchaseは、彼が買った総アイテムです。 uniquePurchaseは、購入したアイテムの種類とは異なります。

これに対して正しいmysqlクエリは何ですか?ヘルプのThx。

+0

ためtaotalPurchase

Count(Distinct hasPurchase)この

Count(hasPurchase)ために、グループを試すことができますか? – Faisal

+0

試したコードを表示してください。 – user1234

答えて

0
SELECT DISTINCT CustomerName, 
       CustomerGroup, 
       COUNT(hasPurchase) as totalPurchase, 
       COUNT(DISTINCT hasPurchase) as uniquePurchase 
FROM XXX 
GROUP BY CustomerName, 
     CustomerGroup 

とともにdistinctcountcountを使用し、CUSTOMERNAMEとcustomerGroupは、各行に対して同じと仮定すると、私は、MySQL上でそれを実行していないが、私はそれが動作するはずだと思います。

+1

thx、それは働いています。 –

0

group by

select customerName 
,customerGroup 
,count(hasPurchase) as totalPurchase 
,count(distinct hasPurchase) as uniquePurchase 
from your_table 
group by CustomerName,CustomerGroup 
0

あなたは、あなたがこれまで試したどのuniquePurchase

SELECT customerName,customerGroup,count(hasPurchase) as totalPurchase,count(distinct hasPurchase) as uniquePurchase 
from table group by CustomerName;