mysql并集和删除半相似行

ev7lccsx  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(402)

我有一个由两个表组成的联合体,一个是死亡率表,一个是临床时间表表。死亡率表最多只能包含每个患者一个条目(原因很明显),时间线可以包含多个条目。
我遇到的问题是,有时用户会将死亡率记录在死亡率表中,有时记录在时间线表中,有时记录在两者中。我不能使用'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

有什么明显的把戏我可以用来击打一个半复制品吗?

j2cgzkjk

j2cgzkjk1#

您可以使用聚合函数来减少行数,例如:groupconcat

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

相关问题