我的数据包含下表:
t1 (results): card_id group_id project_id user_id
包含实际标签的表格为:
t2 (groups): id project_id label
t3 (cards): id project_id label
不同的用户可能会有多个条目。
我需要帮助编写查询以表格格式显示结果,总计数对应卡片/组。这是我的开始,但我不确定我是否在正确的轨道上......
SELECT COUNT(card_id) AS cTotal, COUNT(group_id) AS gTotal
WHERE project_id = $projID
答案 0 :(得分:1)
如果您知道有九个组的固定事实,那么只需在子查询中包含这些组 - 与此类似:
select cTotal, g1.gTotal as Group1, g2.gTotal as Group2... etc
from
( SELECT COUNT(card_id) AS cTotal
, COUNT(group_id) AS gTotal
WHERE project_id = $projID
AND group_id = 1 ) g1
, ( SELECT COUNT(card_id) AS cTotal
, COUNT(group_id) AS gTotal
WHERE project_id = $projID
AND group_id = 2 ) g2
etc.
答案 1 :(得分:1)
除非我弄错了,否则您需要做的就是给出给定project_id的card_id和group_id分组,并为每个组提取计数
SELECT card_id, group_id, COUNT(user_id) FROM mytable
WHERE project_id = 001
GROUP BY (card_id, group_id);
修改强>
考虑到卡和组表涉及一些连接,但查询基本相同。仍然按卡和组进行分组,并按项目ID进行约束
SELECT c.label, g.label, COUNT(t1.user_id) FROM mytable t1
JOIN groups g ON t1.group_id=g.id
JOIN cards c ON t1.card_is=c.id
WHERE t1.project_id = 001
GROUP BY (c.card_id, g.group_id)
ORDER BY (c.card_id, g.group_id);
我认为你不能只用SQL获得一个表。您必须通过迭代结果来在代码中呈现表。如何操作取决于您使用的语言/平台。