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

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

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

问题

select
    sum(case when terminal_id like '911%' then 1 else 0 end) as 911like,
    sum(case when terminal_id like '111%' then 1 else 0 end) as 111like
from table
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:

select count(name) from table
	where
        created_at between
			'2022-12-01' and '2022-12-10' and
        terminal_id like '911%'
select count(name) from table
	where
        created_at between
			'2022-12-01' and '2022-12-10' and
        terminal_id like '111%'

How to write query to get this output:

911like 111like
10 25

答案1

得分: 1

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

选择 count(case when terminal_id like '911%'  
                  then name
               end)  作为 [911like]
       ,count(case when terminal_id like '111%'  
                  then name
               end)  作为 [111like]
   从表中
 其中 created_at 在 '2022-12-01' 和 '2022-12-10' 之间。
英文:

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

select count(case when terminal_id like '911%'  
                  then name
               end)  as [911like]
       ,count(case when terminal_id like '111%'  
                  then name
               end)  as [111like]
   from table
 where created_at between '2022-12-01' and '2022-12-10'

答案2

得分: 1

更简化的版本:

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

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

英文:

More simplified:

select sum(terminal_id like '911%') as 911like,
       sum(terminal_id like '111%') as 111like
from my_table
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:

确定