0

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

这些表是:'shops'、'members'、'membership_cards'。

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

我需要提取按每个商店的成员资格分组的成员数。我可以在不使用服务器端语言的情况下做到这一点吗?

最终结果应该是这样的:

商店名称,n°bronze 会员,n°silver_members,n°gold_members ....

4

3 回答 3

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

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

于 2012-07-17T13:37:59.280 回答
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)
于 2012-07-17T13:38:37.227 回答
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函数以防任何成员没有卡

于 2012-07-17T13:46:01.853 回答