显示具有最大出现次数的组

时间:2017-11-08 13:57:24

标签: mysql sql

t_table看起来像:

+-----------+---------+--------------+------------------+-----------------------+----------------------------------+
| pk_IdLoan | fk_IdCar| fk_IdCustomer| fk_Source_Agency | fk_Destination_Agency | RentalDate | DeliveryDate | Cost |
+-----------+---------+--------------+------------------+-----------------------+----------------------------------+

我写了一个查询:

(SELECT fk_IdCustomer, MONTHNAME(RentalDate) AS Month, YEAR(RentalDate) As Year, COUNT(*)
FROM t_loan
GROUP BY fk_IdCustomer, Month, Year);

导致

+---------------+-------------+------+----------+
| fk_IdCustomer | Month       | Year | COUNT(*) |
+---------------+-------------+------+----------+
| 1             | July        | 2016 | 3        |
| 1             | November    | 2017 | 1        |
| 1             | September   | 2016 | 7        |
| 5             | May         | 2016 | 1        |
| 6             | January     | 2016 | 1        |
| 6             | September   | 2017 | 2        |
+---------------+-------------+------+----------+

现在我希望为每个客户获得这些数月和数年的结果COUNT(*),f.e。:

+---------------+-------------+------+----------+
| fk_IdCustomer | Month       | Year | COUNT(*) |
+---------------+-------------+------+----------+
| 1             | September   | 2016 | 7        |
| 5             | May         | 2016 | 1        |
| 6             | September   | 2017 | 2        |
+---------------+-------------+------+----------+

如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

这在MySQL中有点痛苦,它不支持CTE或窗口功能。一种方法是:

SELECT fk_IdCustomer, MONTHNAME(RentalDate) AS Month,
       YEAR(RentalDate) As Year, COUNT(*) as cnt
FROM t_loan l
GROUP BY fk_IdCustomer, Month, Year
HAVING cnt = (SELECT COUNT(*)
              FROM t_loan l2
              WHERE l2.fk_IdCustomer = l.fk_IdCustomer
              GROUP BY MONTHNAME(RentalDate), YEAR(RentalDate)
              ORDER BY COUNT(*) DESC
              LIMIT 1
             );

注意:如果有重复项,您将获得所有匹配的值。