MySQL - 组中的条件选择

时间:2016-11-25 11:02:48

标签: mysql sql select group-by conditional-statements

我有一个包含多行的简单表格,我希望按id_room对它们进行分组,并仅在条件为真时选择值。问题是条件总是假的,即使有一行有正确的日期列year_month

这是架构:

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。为什么会这样?

2 个答案:

答案 0 :(得分: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 :(得分: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