Jika saya mengerti dengan benar, did_i_buy
kolom berarti "apakah Tom membeli". Anda dapat melakukannya seperti ini:
SELECT
Items.item_id,
item_name,
COUNT(CASE WHEN purchase_status='bought' THEN 1 END) as number_bought,
MAX(CASE WHEN purchase_status='bought' AND user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
GROUP BY Items.item_id
Alternatifnya (satu CASE
pernyataan, lihat komentar di bawah)
SELECT
Items.item_id,
item_name,
COUNT(purchase_status='bought') as number_bought,
MAX(CASE WHEN user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
WHERE purchase_status='bought'
GROUP BY Items.item_id
Dan satu penyesuaian lagi: Karena WHERE
klausa, COUNT
hanya akan melihat baris di mana purchase_status='bought'
, jadi ekspresi yang memeriksa status dapat diabaikan (satu-satunya perubahan dari atas adalah pada baris 4):
SELECT
Items.item_id,
item_name,
COUNT(*) as number_bought,
MAX(CASE WHEN user_name='Tom' THEN 'yes' ELSE 'no' END) AS did_i_buy
FROM Purchases
JOIN Items ON Purchases.item_id=Items.item_id
WHERE purchase_status='bought'
GROUP BY Items.item_id