sql查询在单个cloumn中计算两种类型

时间:2017-08-20 06:04:28

标签: sql

BUSES
----------------
|BUS_NO    
|BUS_NAME
|TYPE
|AVAIL_SEAT

我必须计算有多少ACNON AC巴士?

我对count的查询是:

count(*)bus_count
sum(case when type='ac' then 1 else 0)
sum (case when type="non ac" then 1 else 0)
from buses
group by bus_number;

6 个答案:

答案 0 :(得分:1)

由于数据库表中的内容区分大小写,因此添加小写或大写功能会将type属性的内容转换为小写或大写,并尝试将其与给定值匹配。在这里,我使用了下位功能,但也可以使用上位功能,那么我们必须将类型值指定为'AC'/'NON AC'。

SELECT 
    type AS bus_type,
    CASE
        WHEN LOWER(type) = 'ac' THEN COUNT(type)
        WHEN LOWER(type) = 'non ac' THEN COUNT(type)
    END AS bus_count
FROM
    buses
GROUP BY type;

答案 1 :(得分:0)

假设'类型'中只有2个值。列,以下查询将起作用:

Select type, 
Count (*) as bus_count
From bus
Group by 1; 

答案 2 :(得分:0)

如果您需要同一列上的两个结果,则只需要一个总和

 select  
      sum( case when type ='ac' then 1 else 0 end ) type_ac
    , sum( case when type <>'ac' then 1 else 0 end ) type_not_ac
  from buses 

如果您需要类型列表,Hemant答案就是您需要的

答案 3 :(得分:0)

select type as bus_type,
case when type='ac' then count(type)
     when type='non ac' then count(type) end bus_count
from buses group by type;

答案 4 :(得分:0)

select type as bus_type,count(bus_no) as bus_count 
from buses
group by type
order by bus_count desc;

答案 5 :(得分:0)

select type as bus_type, 

case 

when type='ac' then count(type)

when type='non ac' then count(type)

end as bus_count

from buses

group by bus_type

order by bus_count desc;