1

in table LOG i have the following entries

userid     item     role
1          Apple    Buyer
2          Banana   Seller
3          Apple    Buyer
1          Banana   Seller
3          Orange   Buyer
etc

i'm trying to create the following two tables with SQL. table 1:

 item      countUser1Buy      countUser1Sell
 Apple
 Banana
 Orange

AND TAble 2 (here i mean the mean of totals. as in, the mean of the total apples bought

 item      alluserBuyTotalMean      allUserBuyTotalMedian   allUserBuyRange   allUserBuyStandardDev
 Apple
 Banana
 Orange

i think the first should be a variation on

`SELECT `item`, `role`, count(`item`) as count FROM `LOG` GROUP BY `item`

which is close, giving me

item    role   count
Apple   Buyer   1
Banana  Seller  1

but i cant figure out how to make it as i'm trying to get. the second i'm really stumped. thanks

3 Answers 3

2

You need conditional aggregation for this:

SELECT `item`, 
       COUNT(CASE WHEN role='Seller' THEN 1 END) AS countUserSell,
       COUNT(CASE WHEN role='Buyer' THEN 1 END) AS countUserBuy  
FROM `LOG` 
GROUP BY `item`
Sign up to request clarification or add additional context in comments.

Comments

1

First query:

SELECT item
     , SUM(role = 'Buyer') AS countUser1Buy
     , SUM(role = 'Seller') AS countUser1Sell
  FROM LOG
 WHERE userid = 1
 GROUP BY item;

Second query:

SELECT item
     , AVG(total) AS alluserBuyTotalMean
     , CONCAT(MIN(total), ' - ', MAX(total)) AS allUserBuyRange
     , STDDEV_POP(total) AS allUserBuyStandardDev
  FROM (
       SELECT item
            , COUNT(*) AS total
         FROM LOG
        WHERE role = 'Buyer'
        GROUP BY item, userid
       ) t
 GROUP BY item;

Comments

1
SELECT
`item`
,SUM(CASE WHEN `userid`= 1 AND `role` = 'Buyer' THEN 1 ELSE 0 END) as countUser1Buy
,SUM(CASE WHEN `userid` = 1 AND `role` = 'Seller' THEN 1 ELSE 0 END) as countUser1Sell
FROM `LOG`
GROUP BY Item

You will need to make a new CASE statement for each userid, but this should work. Results in the following:

item    countUser1Buy   countUser1Sell
Apple   1               0
Banana  0               1
Orange  0               0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.