SQL查询计数

时间:2019-03-01 17:56:36

标签: sql

注释表和命令2殖民地。总价不超过0欧元,50欧元,不等51欧元,100欧元和不超过100欧元。 SQL通讯员。

英语版本:

考虑一个包含两列command_idvalue_total的命令表。我们寻求获得总价值在0到50欧元之间,在51到100欧元之间,最终超过100欧元的订单数量。编写相应的SQL查询。
当前代码:

select count(*) from commande where Totale<=50 
Union 
select count(*)from commade where Totale>= 51 AND Totale <=100 
UNION 
select count(*) from commande where Totale>101

2 个答案:

答案 0 :(得分:1)

您可以像这样在一行中获得3个计数器:

select
  sum(case when value_total <= 50 then 1 else 0 end) counter1,
  sum(case when value_total > 50 and value_total <= 100 then 1 else 0 end) counter2,
  sum(case when value_total > 100 then 1 else 0 end) counter3
from commande

另一种将计数器放在单独行中的解决方案,
前提是value_total列为整数将用于 MySql

select 
  case (value_total - 1) div 50 
    when 0 then '(a) <=50'
    when 1 then '(b) >50 and <=100'
    else '(c) >100'
  end category, 
count(*) counter
from commande
group by category;

请参见demo

答案 1 :(得分:0)

您的查询还可以。不过,您应该使用UNION ALL,并添加一列以说明哪个计数属于哪个范围。例如:

select 'few'    as how_many, count(*) from commande where totale <= 50 
union all
select 'medium' as how_many, count(*) from commande where totale > 50 and totale <= 100 
union all
select 'many'   as how_many, count(*) from commande where totale > 100;