【问题标题】:Need help DB Query for this scenario在这种情况下需要帮助数据库查询
【发布时间】:2018-04-20 07:57:16
【问题描述】:

我无法为下表内容派生 SQL 查询。

当我尝试以下查询时,我得到了上述输出。有人可以帮我提供所需的查询吗?

select Name, count(Status) from mytable where Status='Open' group by mytable union
select Name, count(Status) from mytable where Status='Cleared' group by mytable

【问题讨论】:

  • 在选择列表中使用 case 表达式进行条件聚合。

标签: mysql sql sqlite


【解决方案1】:

在选择列表中使用case 表达式进行条件聚合。

select Name,
       count(case when Status = 'Open' then 1 end) as opencnt,
       count(case when Status = 'Cleared' then 1 end) as clearedcnt
from mytable
where Status in ('Open', 'Cleared')
group by Name

COUNT() 计算非空值。当条件不满足时,上面的case 表达式返回 null。

【讨论】:

  • 应该是group by Name 而不是group by mytable
  • 再次感谢 Jarlh,因为我在 SQL 中没有太多的 exp,所以我从来没有机会使用 case 和 count。不过,这确实是一个不错的技巧。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多