复杂的sql查询计数和分组

时间:2016-06-01 19:08:27

标签: mysql sql

LOG中的

我有以下条目

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

我正在尝试使用SQL创建以下两个表。表1:

 item      countUser1Buy      countUser1Sell
 Apple
 Banana
 Orange

AND TAble 2(这里我指的是总数的平均值。如同,购买的苹果总数的平均值

 item      alluserBuyTotalMean      allUserBuyTotalMedian   allUserBuyRange   allUserBuyStandardDev
 Apple
 Banana
 Orange

我认为第一个应该是

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

这很接近,给我

item    role   count
Apple   Buyer   1
Banana  Seller  1

但我无法弄清楚如何制作它,因为我想要得到它。第二个我真的很难过。感谢

3 个答案:

答案 0 :(得分:2)

您需要条件聚合

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`

答案 1 :(得分: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

您需要为每个用户标识创建一个新的CASE语句,但这应该有效。结果如下:

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

答案 2 :(得分:1)

首先查询:

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

第二次查询:

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;