joining columns of same table with different criteria - SQL

前端 未结 1 1742
广开言路
广开言路 2021-01-28 00:27

I am able to query with one condition ( as shown in image below ) but when i query with couple of criterias and trying to create two same columns of same table with different cr

相关标签:
1条回答
  • 2021-01-28 01:12

    So if you want lists of save_line in order by line_id, in different columns according to save_type and execution_id, you need to pivot. There are a few different ways you can do this. Here are a couple that should work no matter what flavor of SQL you are using:

    SELECT line_id, 
    max(CASE WHEN execution_id = '292' and save_type = 'R' then save_line end) R_292,
    max(CASE WHEN execution_id = '286' and save_type = 'R' then save_line end) R_286
    FROM save_output_table
    GROUP BY line_id
    

    or

    SELECT t1.save_line save_line1,
    t2.save_line save_line2
    FROM 
        (SELECT *
        FROM save_output_table
        WHERE save_type = 'R'
        and execution_id = '292'
        ) t1
    
    JOIN (SELECT *
        FROM save_output_table
        WHERE save_type = 'R'
        and execution_id = '286'
        ) t2
    ON t1.line_id = t2.line_id
    

    Note: for the second option, the join only gives complete lists if there are the same number of line_ids for each condition. If there aren't, you should change it to a FULL OUTER JOIN, which wouldn't work in MySQL and possibly others.

    0 讨论(0)
提交回复
热议问题