我有一个如下的虚拟数据集,它是一个记录每个患者标本结果的数据集:
case_id specimen_type_id virus_id specimen_result specimen_collection_date
1 1 4 positive 25/12/2014
1 1 5 positive 25/12/2014
1 1 4 negative 21/01/2015
1 2 4 negative 21/01/2015
1 1 4 negative 23/01/2015
1 2 4 negative 23/01/2015
1 1 4 positive 25/01/2015
1 1 4 negative 26/01/2015
1 1 4 negative 27/01/2015
1 1 5 negative 27/01/2015
case_id
指患者的ID
specimen_type_id
是指采集的标本类型,是血样还是痰样等
virus_id
是我们要查找的病毒类型
specimen_result
标本是否查出病毒(阳性)或未查出(阴性)
specimen_collection_date
是采集标本的时间。
我需要一份显示每个患者的列表:i) 最近的连续阴性标本计数(即中间的阳性结果需要重新计数),ii) 最近的连续阴性标本的最晚日期。像下面这样的东西:
case_id virus_id specimen_type_id count latest_specimen_collection_date
1 4 1 2 27/01/2015
1 5 1 1 27/01/2015
在我的示例中,输出基于数据集的最后 3 行。
我是 MySQL 的新手,我搜索了 MySQL 连续
,代码对我来说有点神秘,有人可以帮忙吗?谢谢!
最佳答案
以下查询大部分用于解决您的问题。它针对特定病例、病毒和样本类型逐行创建连续相同结果的“运行”列表。
set @runn = 0;
set @runv = 'xxx';
SELECT specruns.*,count(*) cnt,MIN(specruns.speciman_date) mindate,MAX(specruns.speciman_date) maxdate
FROM
(
SELECT
IF(@runv = CONCAT(s.case_id,s.speciman_type_id,s.virus_id,s.speciman_result ) ,@runn,@runn:=@runn+1) run,
@runv := CONCAT(s.case_id,s.speciman_type_id,s.virus_id ,s.speciman_result) val,
s.* FROM specs s
ORDER BY s.case_id,s.speciman_type_id,s.virus_id ,s.speciman_date
) specruns
GROUP BY specruns.run
关于mysql - 统计MySQL中 "latest"连续计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977726/