我想对数据库中的一个表执行多个查询。该表的摘要如下:
+-------+-----+
| user | val |
+-------+-----+
| user1 | 1 |
| user2 | 2 |
| null | 5 |
| null | 5 |
| user3 | 5 |
| user1 | 1 |
+-------+-----+
单个查询很简单,但是我很难将它们放在一起。查询如下:
到目前为止,我有这个:
SELECT
( SELECT user from db where user='{someuser}'),
( SELECT COUNT(*) FROM db WHERE user='{someuser}' AND val= '1'),
( SELECT COUNT(*) FROM db WHERE user='{someuser}' AND val= '2');
基本上,我需要将{someuser}替换为用户列中存在的每个用户。
我希望我的输出看起来像这样
+-------+-------+-------+-------+
| user | val=1 | val=2 | total |
+-------+-------+-------+-------+
| user1 | 1 | 1 | 2 |
| user2 | 1 | 0 | 1 |
| user3 | 0 | 0 | 0 |
+-------+-------+-------+-------+
答案 0 :(得分:0)
嗯。 。 。我认为您需要条件聚合:
select user, sum(case when val = 1 then 1 else 0 end) as val_1,
sum(case when val = 2 then 1 else 0 end) as val_2,
count(*) as total
from t
group by user
order by user;