MySQL:根据事件类型计算事件出勤率

时间:2013-11-27 06:08:59

标签: mysql sql group-by

我设置了三张桌子来跟踪参加活动的情况。表格如下:

Users
--------
rid
name

Events
--------
eid
name
type (either 0 or 1)

Attendance
--------
rid
eid

我正在尝试返回所有用户并打印出他们参加过的事件数量的计数,分为类型1和类型0的数量。

我可以使用以下语句成功地返回一个或另一个但不是两者的组合:

SELECT users.name, COUNT(type) as typeCount FROM attendance, events, users
WHERE users.rid=attendance.rid && events.eid=attendance.eid && type=1 GROUP BY users.rid

返回

╔══════╦══════════════╗
║ name ║  typeCount   ║ 
╠══════╬══════════════╣
║ John ║      5       ║
╠══════╬══════════════╣
║ Jack ║      3       ║
╚══════╩══════════════╝

但我希望它返回

╔══════╦══════════════╦═════════════╗
║ name ║  type0Count  ║ type1Count  ║
╠══════╬══════════════╬═════════════╣
║ John ║      2       ║      5      ║
╠══════╬══════════════╬═════════════╣
║ Jack ║      7       ║      3      ║
╚══════╩══════════════╩═════════════╝

2 个答案:

答案 0 :(得分:1)

您可以使用COUNT功能中的CASE...WHEN来计算列中的特定值。

SELECT
    Users.rid,
    Users.Name,
    COUNT(CASE Events.type WHEN 0 THEN 1 ELSE NULL END) AS type0Count,
    COUNT(CASE Events.type WHEN 1 THEN 1 ELSE NULL END) AS type1Count
FROM Users
INNER JOIN Attendance ON Users.rid = Attendance.rid
INNER JOIN Events ON Attendance.eid = Events.eid
GROUP BY Users.rid, Users.Name

您也可以使用IFNULLIF

答案 1 :(得分:0)

你必须从过滤器中取出类型

SELECT users.name,type, COUNT(type) as typeCount 
FROM attendance, events, users
WHERE
users.rid=attendance.rid 
&& events.eid=attendance.eid 
GROUP BY users.rid,type

SELECT users.name, 
CASE WHEN type = 0 THEN COUNT(1) AS type0Count END,
CASE WHEN type = 1 THEN COUNT(1) AS type1Count END 
FROM attendance, events, users
WHERE users.rid=attendance.rid 
&& 
events.eid=attendance.eid
GROUP BY users.rid