选择多个喜欢的计数/总和和年/日的查询组?

时间:2017-09-06 06:52:30

标签: mysql sql database mysqli

我遇到问题解决从多个表中选择计数数据。

我有"租" table作为事务表,就像这样 rent

"客户" table作为主表customer

这是我当前的查询

select 

ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=1)AND (YEAR(rent_date)='2017'))),0) AS `Jan`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=2)AND (YEAR(rent_date)='2017'))),0) AS `Feb`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=3)AND (YEAR(rent_date)='2017'))),0) AS `Mar`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=4)AND (YEAR(rent_date)='2017'))),0) AS `Apr`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=5)AND (YEAR(rent_date)='2017'))),0) AS `May`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=6)AND (YEAR(rent_date)='2017'))),0) AS `Jun`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=7)AND (YEAR(rent_date)='2017'))),0) AS `Jul`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=8)AND (YEAR(rent_date)='2017'))),0) AS `Aug`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=9)AND (YEAR(rent_date)='2017'))),0) AS `Sep`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=10)AND (YEAR(rent_date)='2017'))),0) AS `Oct`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=11)AND (YEAR(rent_date)='2017'))),0) AS `Nov`,
      ifnull((SELECT COUNT(rent_id) FROM (transaction)WHERE((Month(rent_date)=12)AND (YEAR(rent_date)='2017'))),0) AS `Dec`
     from transaction 
     where YEAR(rent_date)='2017'
    GROUP BY YEAR(rent_date) 

我项目中的结果查询就像这样

+-----------+----------+
| Month     | Rent     |
+-----------+----------+
|       Aug |        4 | 
|       Sep |        4 | 
+-----------+----------+

我想改变这样的结果

+-----------+----------+-----------+----------+
| Month     | S        | SS        | SSS      |
+-----------+----------+-----------+----------+
|       Aug |        2 |          1|        1 | 
|       Sep |        2 |          1|        1 | 
+-----------+----------+-----------+----------+

S,SS和SSS列数据来自COUNT rent_id,它从客户表中的customer_status中选择。

我必须对这些结果做出哪些改变? 我不知道应该把JOIN,AS和LIKE放在哪里 或者有更简单的方法来获得这些结果

0 个答案:

没有答案