SQL查询多个COUNT导致值相同(但不正确)

时间:2018-10-30 04:45:39

标签: sql count

我有一个数据集myTable,看起来像这样:

username   saveType

Alice      auto
Alice      auto
Alice      manual
Alice      manual
Bob        auto
Bob        auto
Bob        auto
Bob        auto

我想统计每个用户找到了多少个自动和手动的saveType。 理想情况下,我希望查询结果看起来像这样:

username  AutoCount  ManualCount
Alice     2          2
Bob       4          0

但是当我运行此查询时:

SELECT username, COUNT(saveType="auto") AutoCount, COUNT(savetype="manual") ManualCount
FROM myTable
GROUP BY username

我反而得到了:

username  AutoCount  ManualCount
Alice     4          4
Bob       4          4

数据库为data world。有关此处发生的情况的任何解释都将有所帮助!谢谢!

3 个答案:

答案 0 :(得分:3)

尝试使用CASE WHEN

SELECT 
  username, 
  COUNT(case when saveType='auto' then 1 end) AutoCount, 
  COUNT(case when savetype='manual' then 1 end) ManualCount
FROM myTable
GROUP BY username

答案 1 :(得分:2)

在当前查询中将COUNT替换为SUM,它应该可以工作:

SELECT
    username,
    SUM(saveType='auto')   AutoCount,
    SUM(savetype='manual') ManualCount
FROM yourTable
GROUP BY username;

Demo

COUNT(saveType='auto')的问题在于其中的表达式将求值为0(假)或1(真)。但是,在两种情况下,COUNT都将为其计数1。 SUM通过有效地忽略零值来解决此问题。

答案 2 :(得分:0)

您也可以尝试以下查询:

select r.username, t1.AutoCount, t2.Manualcount from 
yourtable r inner join (select username,  count(saveType) autoCount from yourtable where saveType='auto' group by username) t1
on t1.username = r.username
inner join  (select username,  count(saveType) ManualCount from yourtable where saveType ='manual' group by username) t2
on t2.username = r.username

希望这可以为您提供帮助。