如果同一个人ID重复行值,则需要在不同的列中显示行值

时间:2019-07-13 08:02:38

标签: mysql sql

现在我有这样的输出,但是我需要以不同的方式输出

Peron_id  Diagnosis1 doagnosis2 diagnosis3 diagnosis4 
 1         fever
 2         fever
 2         backpain
 2         UTI

我需要这样的输出

Peron_id  Diagnosis1 doagnosis2 diagnosis3 diagnosis4 
 1         fever
 2         fever     backpain    UTI

请帮助我。

3 个答案:

答案 0 :(得分:1)

如果在mysql中不是必须使用分隔列而不是使用独立的coolumns,则可以尝试使用group_concat在同一行上获取结果

 select person_id, group_concat(Diagnosis1) as diagnosis 
 from my_table  
 group by person_id

答案 1 :(得分:1)

如果您使用的是MySQL 8+,那么我们可以在ROW_NUMBER的帮助下尝试进行数据透视查询:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Peron_id ORDER BY Diagnosis) rn
    FROM yourTable
)

SELECT
    Peron_id,
    MAX(CASE WHEN rn = 1 THEN Diagnosis END) AS Diagnosis1,
    MAX(CASE WHEN rn = 2 THEN Diagnosis END) AS Diagnosis2,
    MAX(CASE WHEN rn = 3 THEN Diagnosis END) AS Diagnosis3,
    MAX(CASE WHEN rn = 4 THEN Diagnosis END) AS Diagnosis4
FROM cte
GROUP BY
    Peron_id;

答案 2 :(得分:0)

您可以在子查询中将conditional aggregationiteration一起使用,

select Person_ID,
       max(case when i = 1 then Diagnosis end) as Diagnosis1,
       max(case when i = 2 then Diagnosis end) as Diagnosis2,
       max(case when i = 3 then Diagnosis end) as Diagnosis3
  from 
  ( 
   select t.Person_ID, t.Diagnosis1 as Diagnosis, 
          @i := IF(@iter = Person_ID, @i + 1, 1) as i,
          @iter := Person_ID
     from tab t
     join (select @iter := null,@i:=0) t2
  ) tt 
group by Person_ID;

+-----------+------------+-------------+------------+
| Person_ID | Diagnosis1 |  Diagnosis2 | Diagnosis3 |
+-----------+------------+-------------+------------+
| 1         | fever      |             |            |
| 2         | fever      | backpain    | UTI        |
+-----------+------------+-------------+------------+

此方法甚至适用于以前的版本。

Demo

编辑 (感谢@GordonLinoff):确实,以上方法给出了所有三个诊断列,它们之间的出现顺序不确定。因此,我认为您还需要一列,例如Diag_order。在这种情况下,最好在下面而不是上面使用此列:

select Person_ID,
       max(case when Diag_order = 1 then Diagnosis1 end) as Diagnosis1,
       max(case when Diag_order = 2 then Diagnosis1 end) as Diagnosis2,
       max(case when Diag_order = 3 then Diagnosis1 end) as Diagnosis3
  from tab t
 group by Person_ID;

+-----------+------------+-------------+------------+
| Person_ID | Diagnosis1 |  Diagnosis2 | Diagnosis3 |
+-----------+------------+-------------+------------+
| 1         | fever      |             |            |
| 2         | fever      | backpain    | UTI        |
+-----------+------------+-------------+------------+