计数(Select * Join)mysql查询

时间:2017-09-29 01:41:16

标签: mysql sql select count

我已经坚持了几个小时,我正在尝试COUNT针对此特定查询的A组,B组,C组中有多少订阅者:

SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
 ( 
     SELECT tbl_gen_info.gen_data_03 
     FROM tbl_subscriber 
     LEFT JOIN tbl_gen_info ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
     WHERE rh.id_subscriber = tbl_subscriber.id_subscriber

 ) AS group_area

FROM tbl_reading_head AS rh
WHERE rh.id_soa_head IS NULL 
AND rh.read_status <> 'Beginning' 
AND rh.rec_status = 'active'
ORDER BY rh.id_subscriber

子查询从gen_data_03

获取组区tbl_gen_info

表包含以下信息:

tbl_gen_info
--------------------------------------------
| gen_category | gen_data_01 | gen_data_03 |
--------------------------------------------
| Area Code    | Camacho St. | Group A     |
--------------------------------------------

tbl_subscriber
----------------------------------
| id_subscriber | bill_area_code | 
----------------------------------
|        1      | Camacho St.    | 
----------------------------------

tbl_reading_head
----------------------------------------------------------------------
| id_subscriber | id_soa_head | read_status | bill_month | bill_year |
----------------------------------------------------------------------
|        1      |     NULL    |   Metered   |     10     |   2017    |
----------------------------------------------------------------------

Query Result

请注意,每个id_subscriber都有两(2)行(一行用于电子,一行用于水)。在按id_subscriber分组后:

GROUP BY rh.id_subscriber

我明白了:

Result

我尝试在子查询之前添加COUNT

  COUNT(SELECT tbl_gen_info.gen_data_03 ...) AS group_area

但这不起作用。

1 个答案:

答案 0 :(得分:1)

使用子查询:

SELECT rh.group_area, COUNT(*)
FROM (SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
             (SELECT tbl_gen_info.gen_data_03 
              FROM tbl_subscriber LEFT JOIN
                   tbl_gen_info
                   ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
             WHERE rh.id_subscriber = tbl_subscriber.id_subscriber
            ) as group_area
      FROM tbl_reading_head rh
      WHERE rh.id_soa_head IS NULL AND
            rh.read_status <> 'Beginning' AND
            rh.rec_status = 'active'
     ) rh
GROUP BY rh.group_area;