在FULL OUTER JOIN中组合结果集

时间:2016-09-30 03:14:49

标签: sql

我有两张桌子:

|ORDER_ID|ORDER_DATE|AMOUNT|
|00000001| 12-SEP-16|   900|
|00000002| 13-SEP-16|  1400|
|00000003| 14-SEP-16|  1000|
|00000004| 15-SEP-16|   700|

|ORDER_ID|PURCHASE_ID|PURCHASE_DATE|AMOUNT|
|00000002|   00000001|    20-SEP-16|  1450|
|00000004|   00000002|    21-SEP-16|   750|

我希望结果如下:

|ORDER_ID|DATE     |AMOUNT_ORDER|AMOUNT_PURCHASE|
|00000001|12-SEP-16|         900|               |
|00000002|20-SEP-16|        1400|           1450|
|00000003|14-SEP-16|        1000|               |
|00000004|21-SEP-16|         700|            750|

到目前为止,我执行此查询:

SELECT 
  a.ORDER_ID,
  CASE WHEN b.ORDER_ID IS NULL
  THEN a.ORDER_DATE
  ELSE b.PURCHASE_DATE
  END AS DATE,
  a.AMOUNT AS AMOUNT_ORDER
  b.AMOUNT AS AMOUNT_PURCHASE
FROM TABLE_A a
FULL OUTER JOIN TABLE_B b
ON a.ORDER_ID = b.ORDER_ID

还有另一种有效的方法来查询吗?

3 个答案:

答案 0 :(得分:0)

根据您的要求,您可以使用LEFT JOIN来实现相同的输出:如果数据必须在两个表中都可用,那么INNER JOIN是最佳方式,这是您可以获得所有连接概览的参考LEFT JOIN vs. LEFT OUTER JOIN in SQL Server希望它会有所帮助。

SELECT 
  a.ORDER_ID,
  CASE WHEN b.ORDER_ID IS NULL THEN a.ORDER_DATE
  ELSE 
  b.PURCHASE_DATE
  END AS DATE,
  a.AMOUNT AS AMOUNT_ORDER
  b.AMOUNT AS AMOUNT_PURCHASE
FROM TABLE_A a
LEFT JOIN TABLE_B b ON a.ORDER_ID = b.ORDER_ID

答案 1 :(得分:0)

如果您希望从两个表中获得完整结果集,则使用完全外部联接。

                select 
                a.ORDER_ID,
                coalesce (a.order_date,b.purchase_date) as DATE,
                a.AMOUNT AS AMOUNT_ORDER,
                b.AMOUNT AS AMOUNT_PURCHASE
                from #table_a a
                full outer join #table_b b on b.ORDER_ID=a.ORDER_ID 
                order by  a.ORDER_ID

如果只想要Table_a的结果,请使用左连接。

            select 
            a.ORDER_ID,
            coalesce (a.order_date,b.purchase_date) as DATE,
            a.AMOUNT AS AMOUNT_ORDER,
            b.AMOUNT AS AMOUNT_PURCHASE
            from #table_a a
            left join #table_b b on b.ORDER_ID=a.ORDER_ID 
            order by  a.ORDER_ID

答案 2 :(得分:0)

SELECT a.ORDER_ID
    ,CASE 
        WHEN b.ORDER_ID IS NULL
            THEN a.ORDER_DATE
        ELSE b.PURCHASE_DATE
        END AS DATE
    ,a.AMOUNT AS AMOUNT_ORDER b.AMOUNT AS AMOUNT_PURCHASE
FROM TABLE_A a
RIGHT JOIN TABLE_B b ON a.ORDER_ID = b.ORDER_ID