我有一张桌子
id|user_id|开始|停止 1| 1| 1| 1 2| 2| 1| 1 3| 2| 1| 0 4| 3| 0| 0
我想得到下一个结果
user_id|总计|开始|停止 1| 1| 1| 1 2| 2| 2| 1 3| 1| 0| 0
所以我想计数 3 并按 user_id ang get 分组。是否可以使用联接而不使用派生表来准备查询?
SELECT user_id,
Sum (start) AS start,
Sum (stop) AS stop,
Count(*) AS total
FROM tablename
GROUP BY user_id
SELECT user_id, COUNT(*) total, SUM(start=1) start, SUM(stop=1) stop
FROM my_table
GROUP BY user_id
总行数为 1 instart
和 1 instop
两次。
SELECT user_id,
count(case start WHEN 1 then 1 else null end) AS start,
count(case stop WHEN 1 then 1 else null end) AS stop,
count (*) AS total
FROM tablename
GROUP BY user_id