使用多个SELECT和GROUP BY进行查询

时间:2013-07-08 06:41:10

标签: mysql sql

我将计算总面积的记录,其中状态会有所不同,如'待定','发送信息','PTP'与分组依据和多个选择查询但结果没有那么多帮助我。

我的查询是:

SELECT AREA, 
(SELECT COUNT( * ) FROM prospectmaster WHERE ZONE = 'AHMEDABAD' && STATUS = 'PENDING' GROUP BY AREA) AS PENDING, 
(SELECT COUNT( * ) FROM prospectmaster WHERE ZONE = 'AHMEDABAD' && STATUS = 'SENT INFO.' GROUP BY AREA) AS CNT 
FROM prospectmaster 
WHERE ZONE = 'AHMEDABAD' GROUP BY AREA  

我想要这种结果。

AREA       PENDING    INFO SENT     PTP 
AHMEDABAD   1          2             1    
GANDHINAGAR 1          5             4
KHEDA       3         10             9

我认为查询中存在一些问题,但我没有得到它。所以,请帮助我。

3 个答案:

答案 0 :(得分:5)

SELECT AREA, 
       SUM(CASE WHEN STATUS = 'PENDING' THEN 1 ELSE 0 END) AS PENDING, 
       SUM(CASE WHEN STATUS = 'SENT INFO.' THEN 1 ELSE 0 END) AS cnt, 
       SUM(CASE WHEN STATUS = 'PTP' THEN 1 ELSE 0 END) AS PTP
  FROM prospectmaster 
 WHERE ZONE = 'AHMEDABAD' 
 GROUP BY AREA;

如果STATUS有“发送信息”。使用.

在数据库中记录

答案 1 :(得分:1)

  SELECT AREA, 
         SUM(if(STATUS='PENDING',1,0)) AS PENDING, 
         SUM(if(STATUS='SENT INFO',1,0)) AS "INFO SENT",
         SUM(if(STATUS='PTP',1,0)) AS PTP 
    FROM prospectmaster 
   WHERE ZONE = 'AHMEDABAD' 
GROUP BY AREA;

答案 2 :(得分:0)

因为这是mysql,所以你可以这样做:

SELECT
  AREA, 
  SUM(STATUS = 'PENDING') AS PENDING, 
  SUM(STATUS = 'SENT INFO.') AS SENT_INFO,
  SUM(STATUS = 'PTP') AS PTP
FROM prospectmaster 
WHERE ZONE = 'AHMEDABAD' 
GROUP BY AREA

这是有效的,因为在mysql中,true为1,false为0,因此求和条件计算其真实的次数