MYSQL如何计算按类型分组的元素

时间:2012-07-17 13:31:53

标签: mysql count group-by

我的查询有问题: 我有一个商店列表,每个商店都有会员,并且有各种类别的会员资格(青铜,银,金...)

表格是:'商店','会员','membership_cards'。

shops: id, name
members: id, shops_id, membership_id, first_name, last_name
membership_cards: id, description

我需要提取成员数,按每个商店的成员资格分组。我可以不使用服务器端语言吗?

最终结果应该是:

商店名称,n°青铜成员,n°silver_members,n°gold_members ....

3 个答案:

答案 0 :(得分:0)

在不知道您的数据库架构的情况下,回答这个问题有点难,但是以下内容应该可以完成这项工作:

SELECT      shop.name,
            SUM(CASE WHEN membership_cards.category = 'Bronze' THEN 1 ELSE 0 END) AS Bronze,
            SUM(CASE WHEN membership_cards.category = 'Silver'THEN 1 ELSE 0 END) AS Silver,
            SUM(CASE WHEN membership_cards.category = 'Gold' THEN 1 ELSE 0 END) AS Gold
FROM        shops
INNER JOIN  members
ON          shop.id = members.shopid
INNER JOIN  membership_cards 
ON          members.id = membership_cards.memberid
GROUP BY    shop.name

只需将列名更改为您正在使用的名称。

答案 1 :(得分:0)

根据您提供的内容,您需要一个类似的查询:

select shopid,
       sum(case when c.cardtype = 'Bronze' then 1 else 0 end) as Bronze,
       sum(case when c.cardtype = 'Silver' then 1 else 0 end) as Silver,
       sum(case when c.cardtype = 'Gold' then 1 else 0 end) as Gold
from shops s left outer join
     members m
     on s.shopid = m.shopid left outer join
     cards c
     on c.memberid = m.memberid
group by shopid

如果你想知道成员的数量,而不是每组中的牌数(如果成员可以有多张牌),那么将sum()表达式替换为:

count(case when c.cardtype = 'Bronze' then m.memberid end)

答案 2 :(得分:0)

SELECT B.name,A.Bronze,A.Silver,A.Gold    
FROM
(
    SELECT S.id,
        SUM(IF(IFNULL(C.cardtype,'')='Bronze',1,0)) Bronze,
        SUM(IF(IFNULL(C.cardtype,'')='Silver',1,0)) Silver,
        SUM(IF(IFNULL(C.cardtype,'')='Gold'  ,1,0)) Gold
    FROM shops S
    LEFT JOIN members M ON S.id = M.shops_id
    LEFT JOIN membership_cards C ON M.membership_id = C.id
    GROUP BY S.id
) A
INNER JOIN shops B USING (id);

我使用IFNULL功能以防任何会员没有卡