我有3张桌子:
user 1 - n (user_id)feedback(type_id) n - 1 word
用户:
id name
1 name1
2 name2
3 name3
4 name4
5 name5
6 name6
反馈:
id user_id type_id title
1 1 1 title1
2 1 1 title2
3 1 2 title3
4 2 1 title4
5 2 2 title5
6 2 2 title6
7 2 1 title7
单词:
id name category
1 great work FEEDBACK_TYPE
2 good work FEEDBACK_TYPE
我尝试通过以下查询来统计每个用户的反馈
结果:
user_id countAllFeedback
1 3
2 4
查询
select
feed.user_id,
count(feed.id) as countAllFeedback
from
feedback feed
group by
feed.user_id;
我想按单词名称计算每个用户的反馈
user_id countAllFeedback countGreatWorkFeedback countGoodWorkFeedback
1 3 2 1
2 4 2 2
请帮助我进行查询^^谢谢
答案 0 :(得分:0)
与用户表无关(根据演示数据)
这可以使用以下查询来实现。...
SELECT b.user_id,c.name,
SUM(b.user_id) AS 'countAllFeedback',
SUM(CASE WHEN c.name='great work' THEN 1 ELSE 0 END) AS 'countGreatWorkFeedback',
SUM(CASE WHEN c.name='good work' THEN 1 ELSE 0 END) AS 'countGoodWorkFeedback'
FROM tbl_Feedback b
LEFT OUTER JOIN
tbl_Word c
ON b.type_id=c.id
GROUP BY b.user_id,c.name
注意:-这里我使用带有求和函数的Case语句
答案 1 :(得分:0)
您可以在下面的脚本中尝试此操作。由于您没有从其他表动态收集的内容,因此不需要连接。您可以将Type_ID用作CASE语句中的静态逻辑,因为这些是Word表中的已知列表。
SELECT A.user_id,
COUNT(*) countAllFeedback,
SUM(CASE WHEN A.type_id = 1 THEN 1 ELSE 0 END) countGreatWorkFeedback,
SUM(CASE WHEN A.type_id = 2 THEN 1 ELSE 0 END) countGoodWorkFeedback
FROM Feedback A
GROUP BY A.user_id
如果有可能更改ID,则可以执行以下操作-
SELECT A.user_id,
COUNT(A.*) countAllFeedback,
SUM(CASE WHEN B.name = 'great work' THEN 1 ELSE 0 END) countGreatWorkFeedback,
SUM(CASE WHEN B.name = 'good work' THEN 1 ELSE 0 END) countGoodWorkFeedback
FROM Feedback A
INNER JOIN Word B ON A.type_id = B.id
GROUP BY A.user_id