嗨,我在下面有这个SQL
数据
CREATE TABLE data
(id int, name varchar(9), room varchar(9), paid varchar(9));
INSERT INTO data
(id, name, room, paid)
VALUES
(1, 'jane', 'room1','0'),
(2, 'any', 'room2', '1'),
(3, 'mandy', 'room2', '1'),
(4, 'vivian', 'room2', '1'),
(5, 'amber', 'room3', '1'),
(6, 'fany', 'room4', '1'),
(7, 'diana', 'room4', '0');
查询
SELECT
data.room, COUNT(data.id) as total
FROM
data
WHERE
data.paid = 0
GROUP BY
data.room
示例链接sqlfiddle
现在的结果是
room 1 = 1
room 4 = 1
我想要的结果
room 1 = 1
room 2 = 0
room 3 = 0
room 4 = 1
任何人都可以帮助我,谢谢
答案 0 :(得分:3)
SELECT
data.room, SUM(data.paid = 0) as total
FROM
data
GROUP BY
data.room;
答案 1 :(得分:2)
SELECT
data.room, SUM(CASE WHEN data.paid = '0' THEN 1 ELSE 0 END) as total
FROM
data
GROUP BY
data.room
请参阅SQLFiddle
答案 2 :(得分:1)
cdaiga的答案是正确的,但依赖于您的值(0
和1
允许您执行SUM
技巧。一般情况下,您希望将原始表格与WHERE
和GROUP BY
生成的表格保持一致。
SELECT DISTINCT original.room, IFNULL(pr.total, 0) AS total
FROM data original LEFT OUTER JOIN (
SELECT
data.room as paidrooms, COUNT(data.id) as total
FROM
data
WHERE
data.paid = 0
GROUP BY
data.room
) as pr on original.room = pr.paidrooms
链接到SQLFiddle
答案 3 :(得分:1)
据我所知,您希望列出所有房间,每个房间都有未付账单。 你冷使用嵌套的选择如下:
SELECT
d1.room,
(SELECT COUNT(d2.room) FROM data d2 WHERE d1.room = d2.room and d2.paid = 0) as total
FROM
data d1
GROUP BY
d1.room