Hvis jeg forstår det rigtigt, er did_i_buy
kolonne betyder "købte Tom". Du kan gøre det sådan her:
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
Alternativt (én CASE
erklæring, se kommentarer nedenfor)
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
Og endnu en tweak: På grund af WHERE
klausulen, COUNT
vil kun se rækker, hvor purchase_status='bought'
, så udtrykket, der kontrollerer status, kan udelades (den eneste ændring fra oven er i linje 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