Faster way to union table SQL

↘锁芯ラ 提交于 2019-12-11 17:09:27

问题


I have TABLE_A

mode          bank_id        amount
'Outgoing'    1              100        
'Incoming'    1              200
'Outgoing'    1              300
'Incoming'    2              200

I need to turn it into

 from_bank_id          to_bank_id        amount
 1                     null              100        
 null                  1                 200
 1                     null              300        
 null                  2                 200

Right now I am doing this

  SELECT 
      amount, 
      NULL AS from_bank_id,
      bank_id AS to_bank_id 
    FROM TABLE_A WHERE mode = 'Incoming'
  UNION ALL
  SELECT 
      amount, 
      NULL AS to_bank_id,
      bank_id AS from_bank_id 
    FROM TABLE_A WHERE mode = 'Outgoing'

This sql works and give me the output I want. Just reaching out to see if there is a better way to achieve this without querying the table twice?

This is the first part query for second part Reducing number of query for inner join when joining base on same table


回答1:


SELECT
    ( CASE WHEN mode = 'Outgoing' THEN bank_id ELSE NULL END ) AS from_bank_id,
    ( CASE WHEN mode = 'Incoming' THEN bank_id ELSE NULL END ) AS to_bank_id,
    amount
FROM
    table_a

PostgreSQL's CASE expression allows ELSE NULL to be omitted with the same behavior (emphasis mine):

https://www.postgresql.org/docs/current/static/functions-conditional.html
If no WHEN condition yields true, the value of the CASE expression is the result of the ELSE clause. If the ELSE clause is omitted and no condition is true, the result is null.

The parentheses can also be omitted:

So the query can be syntactically simplified to:

SELECT
    CASE WHEN mode = 'Outgoing' THEN bank_id END AS from_bank_id,
    CASE WHEN mode = 'Incoming' THEN bank_id END AS to_bank_id,
    amount
FROM
    table_a

...which is slightly more readable.




回答2:


You can accomplish this more efficiently (and easily) with a CASE expression.

select
    case 
        when mode = 'Outgoing' then bank_id 
        else null
    end as from_bank_id
    ,case 
        when mode = 'Incoming' then bank_id 
        else null
    end as to_bank_id
    ,amount
from
    TABLE_A 


来源:https://stackoverflow.com/questions/47231035/faster-way-to-union-table-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!