如何根据每个子渠道的买家数量获得每个主渠道的买家数量

时间:2012-11-12 05:18:51

标签: mysql sql

我需要帮助才能根据每个子渠道

上的买家数量,通过mysql查询获取每个主渠道上的买家数量

基本上我有两个表,即 tbl_channel tbl_buyer ,如下所示:

enter image description here

条件:

  1. 根据每个子渠道
  2. 的买家数量,我只显示每个主渠道(parentid = 0)的买家数量
  3. 具有相同 buyer_id 的channel_id(TBL_BUYER)中的每个买家将被视为一个买家
  4. 我想要的结果:

    enter image description here

    到目前为止,我只能进行查询以显示子频道的买家数量,如下所示:

    SELECT count(aa.buyer_id) as Number_of_buyers FROM (SELECT b.buyer_id
    FROM tbl_channel a 
    RIGHT JOIN tbl_buyer b on (a.id=b.channel_id)
    WHERE a.parentid_channel_id = 2 /* PARENT ID */
    GROUP by b.buyer_id ORDER BY b.channel_id) aa
    

    您可以帮我完成一个完整的查询以产生如上所示的结果吗?谢谢你:)

1 个答案:

答案 0 :(得分:3)

SELECT  a.channel_id `Channel ID`,
        a.channel_title `Channel Title`,
        COUNT(DISTINCT c.buyer_id) `Number of Buyers`
FROM    tbl_Channel a
        INNER JOIN tbl_Channel b
            ON a.channel_ID = b.parent_channel_id
        INNER JOIN tbl_buyer c
            ON  b.channel_ID =  c.channel_ID
WHERE   a.parent_channel_id = 0
GROUP BY a.channel_id,
         a.channel_title