我有一个包含几行的简单表格,我想按 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_month
是 2016-10-01
。为什么会这样?
最佳答案
您当然不需要那个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;
关于MySQL - 组中的条件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803501/