2016-11-25 37 views
1

我有一個簡單的表格,並且我想將它們按id_room分組,並且只有在條件爲真時才選擇值。問題是,即使有一行右列日期列year_month,該條件始終爲假。MySQL - 組中的條件選擇

下面是模式:

CREATE TABLE tbl_account_room (
    `id` int, 
    `year_month` date, 
    `value` int, 
    `id_room` int 
); 

INSERT INTO tbl_account_room 
    (`id`, `year_month`, `value`, `id_room`) 
VALUES 
    (1, '2016-08-01', 1, 300), 
    (2, '2016-09-01', 2, 300), 
    (3, '2016-10-01', 3, 300); 

這裏查詢:

SELECT 
    (case when '2016-10-01' = ar.year_month then ar.value else 0 end) as total 
FROM tbl_account_room AS ar 
WHERE ar.year_month >= "2016-08-01" 
    AND ar.year_month <= "2016-11-01" 
    and ar.id_room = '300' 
GROUP BY ar.id_room 
LIMIT 10 

這裏是SQL Fiddle

total列我越來越0,我想獲得價值3,因爲year_month2016-10-01。爲什麼會發生?

回答

1

你當然不需要那麼CASE條件,包括條件在WHERE條款而不是像

SELECT 
ar.value as total, 
GROUP_CONCAT(ar.year_month) 
FROM tbl_account_room AS ar 
WHERE ar.year_month = '2016-10-01' 
GROUP BY ar.id_room; 
1

不知道爲什麼你要這樣的結果,在這裏你可以使用自聯接來做到這一點:

SELECT 
    MAX(t1.value) as total, 
    GROUP_CONCAT(ar.year_month) 
FROM tbl_account_room AS ar 
LEFT JOIN tbl_account_room AS t1 
ON ar.id_room = t1.id_room 
AND ar.year_month = t1.year_month 
AND t1.year_month = '2016-10-01' 
WHERE ar.year_month >= "2016-08-01" 
    AND ar.year_month <= "2016-11-01" 
    and ar.id_room = '300' 
GROUP BY ar.id_room 
LIMIT 10; 

並且這裏是SQLFiddle Demo