2011-08-08 69 views
0

我正在做一個內部連接,我在日期範圍(比如說,BETWEEN'2011-01-01'和'2011-02-01')之間進行選擇,以及按枚舉值。有沒有一種方法可以在每個月的月份內做一個列?我目前正在每個月手工做這件事。按Enum分組,列爲Date,MySQL

例子:

vehicle_type | January | February | March 
---------------------------------------------- 
sedan   |  12  | 10  | 4 
coupe   |  5  | 7  | 23 
truck   |  0  | 0  | 9 
electric  |  22  | 10  | 13 
hybrid  |  0  | 12  | 0 

回答

0

您可以創建一個日曆表...

CREATE TABLE calendar 
(
    description VARCHAR2(100 BYTE), 
    when_start DATE, 
    when_end  DATE 
) 

然後用一個支點查詢 例如

SELECT 
    vehicle_type, 
    SUM(jan),SUM(feb), 
    --add the other months here 
    SUM(nov),SUM(dece) 
FROM 
(
SELECT v.vehicle_type, 
CASE WHEN c.description='Jan' THEN 
    count(*) 
END AS jan, 
case when c.description='Feb' THEN 
    count(*) 
END AS feb, 
-- Add the rest of the months here too 
CASE WHEN c.description='Nov' THEN 
    COUNT(*) 
END AS nov, 
CASE WHEN c.description='Dec' THEN 
    COUNT(*) 
END AS dece 
FROM calendar c 
INNER JOIN vehicles v ON v.when >= c.when_start AND v.when <= c.when_end 
GROUP BY v.vehicle_type 
) 
GROUP BY vehicle_type 
ORDER BY vehicle_type