SELECT COUNT(*) FROM a WHERE year = 2016 && month = 5 && date = 17 && user = 1
//return 1 row
SELECT COUNT(*) FROM a WHERE year = 2016 && month = 5 && date = 17 && user = 2
//return 0 row
我有2个查询,我需要检查用户1和用户2,用户1必须有1行&用户2必须为0行
我的问题是:是否可以将这两个查询合并在一起
以2列//return 1, 0
答案 0 :(得分:4)
您可以使用sum()
条件来计算条件为真的次数
SELECT SUM(user = 1) as u1,
SUM(user = 2) as u2
FROM a
WHERE year = 2016 and month = 5 and date = 17
答案 1 :(得分:3)
是的,这称为条件聚合:
SELECT count(CASE WHEN `user` = 1 THEN 1 END) as usr1_cnt,
count(CASE WHEN `user` = 2 THEN 1 END) as usr2_cnt
FROM a
WHERE year = 2016 and month = 5 and date = 17
答案 2 :(得分:2)
试试这个:
SELECT SUM(user = 1) AS user1, SUM(user = 2) AS user2
FROM a
WHERE year = 2016 AND month = 5 AND date = 17
SELECT
子句的第一个字段返回user = 1
次出现,而第二个字段返回user = 2
次出现。
答案 3 :(得分:1)
试试这个,
SELECT
(
SELECT COUNT(*)
FROM a
WHERE year = 2016 && month = 5 && date = 17 && user = 1
) AS usr1,
(
SELECT COUNT(*)
FROM a
WHERE year = 2016 && month = 5 && date = 17 && user = 2
) AS usr2
答案 4 :(得分:1)
你也可以尝试这个:
SELECT SUM(user = 1) as user1,
SUM(user = 2) as user2
FROM a
WHERE year = 2016 and month = 5 and date = 17;
答案 5 :(得分:0)
你可以试试这个:
SELECT * from (
SELECT COUNT(*) count1 FROM a WHERE year = 2016 && month = 5 && date = 17 && user = 1) aa,
(SELECT COUNT(*) count2 FROM a WHERE year = 2016 && month = 5 && date = 17 && user = 2) bb;