我有一个联盟,认为这是两个表的组合 - 死亡率表和临床时间表。死亡率表每个患者最多包含一个条目(由于显而易见的原因),时间表可以包含多个条目。
我遇到的问题是,有时候用户会在死亡率表中记录死亡率,有时候会记录在时间表中,有时候记录在两者中。我不能使用' Distinct'关键字,因为行略有不同,因为它们也包含源表名。
因此,我最终会得到这样的东西:
pat_key, date, event, source
1, 2018-03-01, died, p_mortality
1, 2018-03-01, died, p_events
1, 2018-02-01, admitted, p_events
联盟非常简单 - 例如
select pat_key, mmdate as `date`, 'died' as event, 'p_mortality' as source from p_mortality
union distinct
select pat_key, evdate as `date`, evevent as event, 'p_timeline' as source from p_timeline
有什么明显的技巧可以用来破坏其中一个半重复的东西吗?
答案 0 :(得分:1)
您可以使用聚合函数减少行,例如:group_concat
select pat_key, `date`, event, group_concat(source)
from
(
select pat_key, mmdate as `date`, 'died' as event, 'p_mortality' as source from p_mortality
union
select pat_key, evdate as `date`, evevent as event, 'p_timeline' as source from p_timeline
) t
group by pat_key, `date`, event