基于id合并行

时间:2015-05-06 15:45:37

标签: mysql sql

我有一个包含多行的表,例如:

ID    Diagnosis      Procedure
1     2              A
1     4              B

我想这样做,输出是:

ID    DiagnosisAndProcedures
1     2, A, 4, B

我想知道,实现这一目标的最有效方法是什么。谢谢您的帮助!!

SELECT PatientID, GROUP_CONCAT(CONCAT(DiagnosisCodeType, ', ', Procedures) SEPARATOR ', ') AS DiagnosisAndProcedures
FROM (SELECT PatientID, DiagnosisCodeType, GROUP_CONCAT(ProcedureID SEPARATOR ', ') AS Procedures
      FROM (SELECT revenue.HCPCCode, revenue.HCPCCodeCount, patient.*, icd9.DiagnosisCodeType, procedures.ProcedureID, procedures.ProcedureDate, claims.ClaimThroughDate, icd9.ICDAccessCode
FROM database.revenue revenue
RIGHT OUTER JOIN database.patient patient
    ON revenue.ClaimID = patient.ClaimID
JOIN database.diagnosisicd9 icd9
    ON revenue.ClaimID = icd9.ClaimID
JOIN database.claims claims
    ON revenue.ClaimID = claims.ClaimID
JOIN database.procedures procedures
    ON revenue.ClaimID = procedures.ClaimID
AND revenue.HCPCCode IN (659, 698, 5116, 5118, 5122, 5123, 5127, 12164, 12171, 16976, 17283) 
      GROUP BY PatientID, DiagnosisCodeType) AS subquery
GROUP BY PatientID
limit 10;

1 个答案:

答案 0 :(得分:5)

使用CONCATGROUP_CONCAT

SELECT ID, GROUP_CONCAT(CONCAT(Diagnosis, ', ', Procedure) SEPARATOR ', ') AS DiagnosisAndProcedures
FROM YourTable
GROUP BY ID

对于注释中的表,首先使用子查询连接相同ID和诊断的所有过程,然后使用外部查询连接相同ID的所有诊断和过程。

SELECT ID, GROUP_CONCAT(CONCAT(Diagnosis, ', ', Procedures) SEPARATOR ', ') AS DiagnosisAndProcedures
FROM (SELECT ID, Diagnosis, GROUP_CONCAT(Procedure SEPARATOR ', ') AS Procedures
      FROM YourTable
      GROUP BY ID, Diagnosis) AS subquery
GROUP BY ID