PostgreSQL: how to combine multiple rows?

前端 未结 2 818
-上瘾入骨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 06:42

    While I was reading about "simulating row_number", I tried to figure out another way to do this.

    SELECT client_id,  
           MAX( CASE seq WHEN 1 THEN result ELSE '' END ) AS result1,  
           MAX( CASE seq WHEN 2 THEN result ELSE '' END ) AS result2,  
           MAX( CASE seq WHEN 3 THEN result ELSE '' END ) AS result3,  
           MAX( CASE seq WHEN 4 THEN result ELSE '' END ) AS result4,  
           MAX( CASE seq WHEN 5 THEN result ELSE '' END ) AS result5  
    FROM ( SELECT p1.client_id, 
                  p1.result,  
                  ( SELECT COUNT(*)  
                    FROM labresults p2  
                    WHERE p2.client_id = p1.client_id  
                    AND p2.result <= p1.result )  
           FROM labresults p1 
    ) D ( client_id, result, seq )  
    GROUP BY client_id;  
    

    but the query took 10 minutes (500,000 ms++). for 30,000 records. This is too long..

提交回复
热议问题