mariadb 如何在按ID分组后基于列值对行进行计数

xghobddn  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(138)

如何根据列值返回总行数,列值按以下方式分组,下面的代码可以工作,并打印不同的团队及其项目所有权,但total_member计数不正确,比实际值高出约10倍,看起来像每个CASE WHEN都乘以行计数。
下面是我的代码:

SELECT
    team.team_name,
    team_rank.points,
    SUM(CASE WHEN items.item_id = 1 THEN items.count END) AS item1,
    SUM(CASE WHEN items.item_id = 2 THEN items.count END) AS item2,
    SUM(CASE WHEN items.item_id = 3 THEN items.count END) AS item3,
    SUM(CASE WHEN items.item_id = 4 THEN items.count END) AS item4,
    COUNT(member.team_id) AS total_members
FROM
    member
INNER JOIN 
    items ON member.obj_Id = items.owner_id
INNER JOIN 
    team ON team.team_id = member.team_id
JOIN 
    team_rank ON team.team_id = team_rank.team_id 
GROUP BY
    member.team_id

下面是目前结果,项目计算是正确,但实际上第一队只有19名队员,第二队有5名队员,所以要乘以很多倍

编辑日期:
请参见fiddle中按要求上传的示例数据库数据。https://www.db-fiddle.com/f/gwWCEa3vaPs1JTgBnwk1wM/0

ig9co6j1

ig9co6j11#

member内聚合以获取total_members并将结果联接到查询:

SELECT
    team.team_name,
    team_rank.points,
    SUM(CASE WHEN items.item_id = 1 THEN items.count END) AS item1,
    SUM(CASE WHEN items.item_id = 2 THEN items.count END) AS item2,
    SUM(CASE WHEN items.item_id = 3 THEN items.count END) AS item3,
    SUM(CASE WHEN items.item_id = 4 THEN items.count END) AS item4,
    c.total_members
FROM member
INNER JOIN (SELECT team_id, COUNT(team_id) total_members FROM member GROUP BY team_id) c
ON c.team_id = member.team_id
INNER JOIN items ON member.obj_Id = items.owner_id
INNER JOIN team ON team.team_id = member.team_id
INNER JOIN team_rank ON team.team_id = team_rank.team_id 
GROUP BY member.team_id;

请参阅demo

相关问题