如何在同一张表中多次使用 SQL 的 count() 函数并带有 where 子句。

huangapple go评论85阅读模式
英文:

how to use sql count() function multiple times in same table with where clause

问题

  1. select
  2. sum(case when terminal_id like '911%' then 1 else 0 end) as 911like,
  3. sum(case when terminal_id like '111%' then 1 else 0 end) as 111like
  4. from table
  5. where created_at between '2022-12-01' and '2022-12-10';
英文:

Let's say I have a table:

name number date
name1 91104 '2022-12-01'
name2 11161 '2022-12-02'

I am writing these queries:

  1. select count(name) from table
  2. where
  3. created_at between
  4. '2022-12-01' and '2022-12-10' and
  5. terminal_id like '911%'
  1. select count(name) from table
  2. where
  3. created_at between
  4. '2022-12-01' and '2022-12-10' and
  5. terminal_id like '111%'

How to write query to get this output:

911like 111like
10 25

答案1

得分: 1

这是使用 count("expression") 完成的。当表达式为真时,将计数。

  1. 选择 count(case when terminal_id like '911%'
  2. then name
  3. end) 作为 [911like]
  4. ,count(case when terminal_id like '111%'
  5. then name
  6. end) 作为 [111like]
  7. 从表中
  8. 其中 created_at '2022-12-01' '2022-12-10' 之间。
英文:

This is done using count("expression"). This will count when the expression is true

  1. select count(case when terminal_id like '911%'
  2. then name
  3. end) as [911like]
  4. ,count(case when terminal_id like '111%'
  5. then name
  6. end) as [111like]
  7. from table
  8. where created_at between '2022-12-01' and '2022-12-10'

答案2

得分: 1

更简化的版本:

  1. select sum(terminal_id like '911%') as 911like,
  2. sum(terminal_id like '111%') as 111like
  3. from my_table
  4. where created_at between '2022-12-01' and '2022-12-10';

链接:https://dbfiddle.uk/PqdCP0Fq

英文:

More simplified:

  1. select sum(terminal_id like '911%') as 911like,
  2. sum(terminal_id like '111%') as 111like
  3. from my_table
  4. where created_at between '2022-12-01' and '2022-12-10';

https://dbfiddle.uk/PqdCP0Fq

huangapple
  • 本文由 发表于 2023年1月9日 17:42:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定