选择

时间:2016-03-13 04:17:57

标签: mysql group-by subquery

我有这个选择声明:

SELECT p.WPD, count(b.PID) as ParcelsPerBlck, 
(SELECT count(PID) 
FROM bos05eb 
WHERE ptype BETWEEN 009 AND 133) as ResdOnly 
FROM ebos_parcels05 p, bos05eb b 
WHERE p.PID_LONG = b.PID
GROUP BY p.WPD;

我希望select语句中的子查询结果也按p.WPD分组。但是我在每行中得到查询结果如下:

WPD           ParcelsPerBlck    ResdOnly
01-02-030     38                6198
01-08-035     56                6198    
01-04-060     11                6198

等等。

子查询的结果是否可以分组,以便我只获得每行的子查询ResdOnly的结果计数?

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合,而无需相关子查询:

select 
    p.WPD, 
    count(b.PID) as ParcelsPerBlck, 
    sum(case when b.ptype between 009 AND 133 then 1 else 0 end) as ResdOnly 
from 
    ebos_parcels05 p
join 
    bos05eb b on p.PID_LONG = b.PID
group by 
    p.WPD

请注意显式join语法的使用 - 无需在from子句中使用逗号。