我对 mysql Ver 14.14 Distrib 5.5.35 上的这个 mysql 查询有疑问:
我有一个名为mytable 的表date
,其中包含 3 列value
和id_patient
.
CREATE TABLE `mytable`
( `date` DATE NOT NULL
, `id_patient` INT(11) NOT NULL
, `value` INT(3) NULL DEFAULT NULL
);
INSERT INTO `mytable` (`date`, `id_patient`, `value`) VALUES
('2019-11-17', '87321', '6'),
('2019-11-18', '87321', '1'),
('2019-11-19', '87321', '2'),
('2019-11-20', '87321', NULL),
('2019-11-21', '87321', '5'),
('2019-11-22', '87321', '8'),
('2019-11-23', '87321', NULL),
('2019-11-24', '87321', '3'),
('2019-11-25', '87321', '4'),
('2019-11-26', '87321', '6'),
('2019-11-27', '87321', '1'),
('2019-11-28', '87321', '10');
对于每一行,我需要知道第 4 个先前值的总和不为空。
SELECT @date:=date, value,
( SELECT SUM(value)
FROM mytable
WHERE date<@date
AND id_patient=87321
AND value IS NOT NULL
ORDER BY date DESC LIMIT 0,4 ) somme
FROM mytable
WHERE id_patient=87321
它不起作用。无论ORDER BY date DESC LIMIT 0,4
是否选择当前行之前的每一行,结果都是相同的。
有人知道为什么吗?
有一个预期结果的例子:
+-------------+--------------------+--------+
| @date:=date | value | somme |
+-------------+--------------------+--------+
| 2019-11-17 | 6 | NULL | SUM OF 0 previous values not null
| 2019-11-18 | 1 | 6 | SUM OF 1 previous values not null
| 2019-11-19 | 2 | 7 | SUM OF 2 previous values not null
| 2019-11-20 | NULL | 9 | SUM OF 3 previous values not null
| 2019-11-21 | 5 | 9 | SUM OF 4 previous values not null
| 2019-11-22 | 8 | 14 | SUM OF 4 previous values not null
| 2019-11-23 | NULL | 16 | SUM OF 4 previous values not null
| 2019-11-24 | 3 | 16 | SUM OF 4 previous values not null
| 2019-11-25 | 4 | 18 | SUM OF 4 previous values not null
| 2019-11-26 | 6 | 20 | SUM OF 4 previous values not null
| 2019-11-27 | 1 | 21 | SUM OF 4 previous values not null
| 2019-11-28 | 10 | 14 | SUM OF 4 previous values not null
+-------------+--------------------+--------+
谢谢你的帮助 :)
使用自连接和聚合:
select m.date, m.id_patient, m.value,
sum(mm.value) somme
from mytable m left join mytable mm
on mm.id_patient = m.id_patient and mm.value is not null and mm.date < m.date
and (
select count(*) from mytable
where id_patient = m.id_patient and value is not null
and date >= mm.date and date < m.date
) <= 4
where m.id_patient = '87321'
group by m.date, m.id_patient, m.value
请参阅演示。
结果:
| date | id_patient | value | somme |
| ---------- | ---------- | ----- | ----- |
| 2019-11-17 | 87321 | 6 | |
| 2019-11-18 | 87321 | 1 | 6 |
| 2019-11-19 | 87321 | 2 | 7 |
| 2019-11-20 | 87321 | | 9 |
| 2019-11-21 | 87321 | 5 | 9 |
| 2019-11-22 | 87321 | 8 | 14 |
| 2019-11-23 | 87321 | | 16 |
| 2019-11-24 | 87321 | 3 | 16 |
| 2019-11-25 | 87321 | 4 | 18 |
| 2019-11-26 | 87321 | 6 | 20 |
| 2019-11-27 | 87321 | 1 | 21 |
| 2019-11-28 | 87321 | 10 | 14 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句