如何根据列值返回总行数,列值按以下方式分组,下面的代码可以工作,并打印不同的团队及其项目所有权,但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
1条答案
按热度按时间ig9co6j11#
在
member
内聚合以获取total_members
并将结果联接到查询:请参阅demo。