将SQL Query简化为sql语句

时间:2011-12-09 13:58:54

标签: mysql sql

tblticket

ID问题状态
1测试1
2测试2
3测试3

我想根据状态1,2,3等找到计数

我写了3个sql语句如下

从状态= 1的票证中选择计数(*) 从状态= 2的票证中选择计数(*) 从状态= 3的票证中选择计数(*)

将此简化为单一查询的任何方式

2 个答案:

答案 0 :(得分:4)

简单的答案是

select count(*), status
from ticket
group by status

但是,如果您没有状态行,则会产生不同的结果,因为此处记录了此行为:Does COUNT(*) always return a result?

假设只有3个状态值,你可以这样做:

select count(t.status), s.status
from
   (SELECT 1 AS status UNION  ALL SELECT 2 UNION  ALL SELECT 3) s
   LEFT JOIN
   ticket t ON s.status = t.status 
group by
   s.status

..或使用单独的状态查找表:

select  count(t.status), s.status
from
   (SELECT DISTINCT status FROM status) s
   LEFT JOIN
   ticket t ON s.status = t.status 
group by
   s.status

答案 1 :(得分:3)

SELECT status, COUNT(*)
FROM tblticket
GROUP BY status

如果你真的只想要这三种状态,你也可以这样做:

SELECT status, COUNT(*)
FROM tblticket
WHERE status IN (1, 2, 3)
GROUP BY status