真的很簡單(在這裏找不到示例)。基本上我想添加缺失月份的空值。如果有0個實體,則用空值來表示月份的Mysql組
目前我有
|month| total |
----------------
2 | 2454.34
3 | 1254.34
在哪裏,因爲我想
|month| total |
----------------
1 | 0
2 | 2454.34
3 | 1254.34
4 | 0
5 | 0
6 | 0
等。
我的查詢到目前爲止
SELECT MONTH(bookings.booking) as month, SUM(bookings.tendered) as total
FROM bookings
INNER JOIN salons ON salons.id = bookings.salon_id
WHERE bookings.paid = 1
AND YEAR(bookings.booking) = 2017
GROUP BY MONTH(bookings.booking)
ORDER BY MONTH(bookings.booking);
我曾嘗試以下,但似乎並沒有工作,我希望它的方式?從例如
SUM(IF(MONTH(bookings.booking) = 'Jan', bookings.tendered, 0)) AS 'Jan',
SUM(IF(MONTH(bookings.booking) = 'Feb', bookings.tendered, 0)) AS 'Feb',
SUM(IF(MONTH(bookings.booking) = 'Mar', bookings.tendered, 0)) AS 'Mar',
SUM(IF(MONTH(bookings.booking) = 'Apr', bookings.tendered, 0)) AS 'Apr',
SUM(IF(MONTH(bookings.booking) = 'May', bookings.tendered, 0)) AS 'May',
SUM(IF(MONTH(bookings.booking) = 'Jun', bookings.tendered, 0)) AS 'Jun',
SUM(IF(MONTH(bookings.booking) = 'Jul', bookings.tendered, 0)) AS 'Jul',
SUM(IF(MONTH(bookings.booking) = 'Aug', bookings.tendered, 0)) AS 'Aug',
SUM(IF(MONTH(bookings.booking) = 'Sep', bookings.tendered, 0)) AS 'Sep',
SUM(IF(MONTH(bookings.booking) = 'Oct', bookings.tendered, 0)) AS 'Oct',
SUM(IF(MONTH(bookings.booking) = 'Nov', bookings.tendered, 0)) AS 'Nov',
SUM(IF(MONTH(bookings.booking) = 'Dec', bookings.tendered, 0)) AS 'Dec',
SUM(tendered) AS total
修訂
select `a`.`month` as `month_int`, IFNULL(SUM(bookings.tendered), 0) as total from `bookings` right join (
SELECT 1 as month
UNION SELECT 2 as month
UNION SELECT 3 as month
UNION SELECT 4 as month
UNION SELECT 5 as month
UNION SELECT 6 as month
UNION SELECT 7 as month
UNION SELECT 8 as month
UNION SELECT 9 as month
UNION SELECT 10 as month
UNION SELECT 11 as month
UNION SELECT 12 as month\n
) a on `a`.`month` = MONTH(bookings.booking) where `bookings`.`paid` = ? and date(`bookings`.`booking`) > ? and `salon_id` in (?, ?, ?) group by `a`.`month`
你可以將你的查詢留給'(SELECT 1 AS Month UNION ALL SELECT 2 ... UNION ALL SELECT 12)' – shmosel
@shmosel這是一個好主意,謝謝我會給它一個! Laravel查詢生成器是不是那個greeet – sourRaspberri