req_type在一个查询中明智地计数id

时间:2018-01-11 06:22:02

标签: mysql sql sql-server

我有一个SQL查询问题。我不想为同样的结果执行三次查询。

在我的表中,我有一个字段req_type,它有三个参数, 1,2,3。

我想在一个查询中使用基于req_type的计数器,而不是像下面那样执行3次查询

select count(id) as premium FROM tablename where req_type=1
select count(id) as premium1 FROm tablename where req_type=2
select count(id) as premium2 FROm tablename where req_type=3

我被困住,有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

您可以将case用于此类计数

select sum(case when req_type=1 then 1 else 0 end) as premium,
sum(case when req_type=2 then 1 else 0 end) as premium1,
sum(case when req_type=3 then 1 else 0 end) as premium2
FROM tablename 

答案 1 :(得分:1)

使用group by cluase

使用一个查询而不是三个查询
select req_type , count(id) as premium 
FROM tablename 
where req_type in (1,2,3)
group by req_type 

答案 2 :(得分:0)

使用GROUP BY

SELECT req_type, COUNT(id) AS count_premium
FROM tablename
GROUP BY req_type;