如何基于月份联接表

时间:2020-02-12 17:47:42

标签: mysql sql

我正在尝试获取每个月的约会次数。

结果分为12个月的滚动图每月。

我有以下查询:

SELECT a.time AS appointmentdatetime,
       m.text AS ref_month_text,
       m.month AS ref_month_int,
       YEAR(TIME) AS appointmentyear,
       COUNT(a.id) AS COUNT
FROM ref_months m LEFT JOIN
     appointment a
     ON m.month = MONTH(a.time) AND
        a.time >= DATE_ADD(NOW(), INTERVAL - 12 MONTH)
        AND a.dealershipid = '1' AND a.dealerstatus != 'No-Show'
GROUP BY m.month
ORDER BY appointmentyear ASC, m.month ASC

这是结果:

+----------------+--------------------+-------+--+
| ref_month_text | appointmentyear    | COUNT |  |
+----------------+--------------------+-------+--+
| February       |               2019 |    16 |  |
| March          |               2019 |    18 |  |
| April          |               2019 |    10 |  |
| May            |               2019 |    15 |  |
| June           |               2019 |    18 |  |
| July           |               2019 |    10 |  |
| August         |               2019 |    12 |  |
| September      |               2019 |    20 |  |
| October        |               2019 |     7 |  |
| November       |               2019 |    13 |  |
| December       |               2019 |     7 |  |
| January        |               2020 |    11 |  |
+----------------+--------------------+-------+--+

我得到的是按月分组,连续12个月,当没有数据时显示为空,但是我遇到的问题是每个月的计数都是错误的。

例如。 2019年3月应该是20。

我尝试了JOIN类型的所有变体。但是仍然返回错误的数字。

1 个答案:

答案 0 :(得分:1)

我简化了您的查询

SELECT
    YEAR(a.time) AS year,
    ANY_VALUE(MONTHNAME(a.time)) AS month,
    ANY_VALUE(COUNT(a.id)) AS counter,
    MONTH(a.time) AS mo
FROM
    appointment AS a 
GROUP BY
    year,mo
ORDER BY
    year ASC,
    mo ASC