PostgreSQL: how to combine multiple rows?

前端 未结 2 817
-上瘾入骨i
-上瘾入骨i 2021-02-04 06:31

I have a table like this to save the results of a medical checkup and the date of the report sent and the result. Actually the date sent is based on the clinic_visit date. A cli

2条回答
  •  野性不改
    2021-02-04 07:04

    I suggest the following approach:

    SELECT client_id, array_agg(result) AS results
        FROM labresults
        GROUP BY client_id;
    

    It's not exactly the same output format, but it will give you the same information much faster and cleaner.

    If you want the results in separate columns, you can always do this:

    SELECT client_id,
           results[1] AS result1,
           results[2] AS result2,
           results[3] AS result3
    FROM
    (
        SELECT client_id, array_agg(result) AS results
            FROM labresults
            GROUP BY client_id 
    ) AS r
    ORDER BY client_id;
    

    although that will obviously introduce a hardcoded number of possible results.

提交回复
热议问题