我设置了三张桌子来跟踪参加活动的情况。表格如下:
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 ║
╚══════╩══════════════╩═════════════╝
答案 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
您也可以使用IF
或NULLIF
。
答案 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