我有两张桌子:
上下文:
我尝试返回范围内所有月份的值,即使对于shine_orders中的特定app_id,某些月份也没有行。后者是我挣扎的。我不能让它返回结果为0的数据。
到目前为止SQL语句:
SELECT DATE_FORMAT(dt, '%b %y') as dtstr, COUNT(*)
FROM shine_orders
LEFT JOIN LU_CALENDAR
ON Date(shine_orders.dt) = LU_CALENDAR.Calendar_Date
WHERE shine_orders.type = 'PayPal'
AND shine_orders.app_id = '5'
AND DATE_ADD(LU_CALENDAR.Calendar_Date, INTERVAL 2 YEAR) > NOW()
GROUP BY dtstr
ORDER BY DATE_FORMAT(dt, '%y%m') ASC
示例输出:
这里的任何人都有任何想法,我做错了吗?
答案 0 :(得分:1)
首先,您似乎在示例输出中有所有月份。但我明白你的问题是有几个月被跳过,因为示例输出为零。
我认为在这种情况下,右连接将是合适的,而不是左连接,这应该意味着显示字段calendar_date中的每一行。此外,由于您正确地加入LU_CALENDAR表,因此您需要确保按LU_CALENDAR中的内容进行分组。所以对于你的第一行尝试:
SELECT DATE_FORMAT(Calendar_Date, '%b %y') as dtstr, COUNT(*)
答案 1 :(得分:0)
这似乎可以解决问题:
SELECT DATE_FORMAT(LU_CALENDAR.Calendar_Date, '%b %y') as dtstr, IFNULL(COUNT(shine_orders.id),0) as COUNT
FROM shine_orders
RIGHT JOIN LU_CALENDAR
ON LU_CALENDAR.Calendar_Date = Date(shine_orders.dt)
AND shine_orders.app_id = '5'
WHERE LU_CALENDAR.Calendar_Date
BETWEEN DATE(DATE_SUB(NOW() , INTERVAL 2 year)) AND DATE(NOW())
GROUP BY DATE_FORMAT(LU_CALENDAR.Calendar_Date, '%y%m')
ORDER BY DATE_FORMAT(LU_CALENDAR.Calendar_Date, '%y%m') ASC