mysql查询使用单个查询检索计数

时间:2014-03-26 06:13:12

标签: mysql

我在执行以下查询时得到以下结果:

select * from db1.user_details;

Dept_Id     Form_Id     Status
-----------------------------------------------
dept1       Form1       CD1
dept1       Form2       CD1
dept1       Form3       CD2
dept2       Form1       CD1
dept3       Form3       CD2
dept3       Form1       CD1
dept3       Form2       CD3
----------------------------------------------

CD1是"收到",CD2是"在处理",CD3是"拒绝"。

现在我想找出每个部门的收到,正在处理和拒绝的总数

结果应该是:

Dept_Id Received    In Process  Rejected
-------------------------------------------------------------
dept1       2       1             0
dept2       1       0             0
dept3       1       1             1
-------------------------------------------------------------

我无法为此编写mysql查询。任何帮助都非常值得赞赏。

3 个答案:

答案 0 :(得分:2)

您可以使用SUM()条件来获取计数,使用SUM中的条件将导致布尔值,您可以获得计数

select Dept_Id,
SUM(`Status`='CD1') Received,
SUM(`Status`='CD2') In_Process,
SUM(`Status`='CD3') Rejected
from Table1
GROUP BY Dept_Id

Fiddle

答案 1 :(得分:1)

SELECT Dept_Id,,
    SUM(status = 'CD1') as Received,
    SUM(status = 'CD2') as In_Process,
    SUM(status = 'CD3') as Rejected
FROM 
    tablneme
GROUP BY Dept_Id

SQL FIDDLE

enter image description here

答案 2 :(得分:0)

使用IF控制流语句,如下所示:

SELECT Dept_Id,
  SUM(IF(Status='CD1', 1, 0)) AS Received, 
  SUM(IF(Status='CD2', 1, 0)) AS InProcess,
  SUM(IF(Status='CD3', 1, 0)) AS Rejected
FROM db1.user_details
GROUP BY Dept_Id