要求基本的Query语法

时间:2013-06-13 19:09:31

标签: sql oracle

我有两张桌子:

  • 表A:
Order_Date   Order_Amt   Order_Cnt
06/01/13        50.00        2
06/02/13        30.00        1
  • 表B:
Waiver_Date   Waiver_Amt   Waiver_Cnt
06/01/13        25.00        1
06/05/13        15.00        1

我只是希望查询语法产生以下结果(将具有相同日期的记录合并到一行中,保留带有空占位符的不匹配行):

  • 查询结果:
Report_Date   Order_Amt   Order_Cnt     Waiver_Amt     Waiver_Cnt
06/01/13        50.00        2             25.00          1
06/02/13        30.00        1              null         null
06/05/13        null        null           15.00          1

关于如何将Order_date和Waiver_date合并为一个Report_date,我是如此。我相信这对那里的人来说是明智的选择!

提前致谢! ķ。

3 个答案:

答案 0 :(得分:2)

这看起来像是一个完整的外部联接。如果连接列在两个表中都具有相同的名称,那么将问题“将Order_date和Waiver_date合并为一个Report_date”部分就会消失:

SELECT Report_date, Order_amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
  FROM tableA FULL OUTER JOIN tableB USING (Report_date)

由于列的命名方式不同,您需要On - 语法并合并两列,例如COALESCE

SELECT COALESCE(Order_date, Waiver_date) AS Report_Date, Order_amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
  FROM tableA FULL OUTER JOIN tableB ON tableA.Order_Date = tableB.Waiver_Date

现在,如果您的SQL方言缺少完整的外连接,您可以使用左外连接和右外连接的并集对其进行建模:

SELECT order_date AS Report_Date, Order_amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
  FROM tableA LEFT OUTER JOIN tableB ON tableA.Order_Date = tableB.Waiver_Date
UNION 
SELECT Waiver_date AS Report_Date, Order_amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
  FROM tableA RIGHT OUTER JOIN tableB ON tableA.Order_Date = tableB.Waiver_Date

答案 1 :(得分:1)

假设你使用MySQL。您可以使用JOIN来组合具有公共值的列:

SELECT Order_Date AS Report_Date, Order_Amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
FROM A LEFT JOIN B ON Order_Date = Waiver_Date
  UNION
SELECT Order_Date AS Report_Date, Order_Amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
FROM A RIGHT JOIN B ON Order_Date = Waiver_Date;

结帐demo here

如果您的数据库支持完全外连接(例如PostgreSQL),则以下内容也适用:

SELECT Order_Date AS Report_Date, Order_Amt, Order_Cnt, Waiver_Amt, Waiver_Cnt
FROM A OUTER JOIN B ON Order_Date = Waiver_Date;

答案 2 :(得分:0)

我在Sql Server中复制了你的表结构,这似乎有效:

SELECT IsNull(A.Order_Date, B.Waiver_Date) AS Report_Date, Order_Amt, Order_Cnt,  Waiver_Amt, Waiver_Cnt
FROM B
RIGHT JOIN A ON A.Order_Date=B.Waiver_Date
UNION
SELECT IsNull(A.Order_Date, B.Waiver_Date) AS Report_Date, Order_Amt, Order_Cnt,  Waiver_Amt, Waiver_Cnt
FROM A
RIGHT JOIN B ON A.Order_Date=B.Waiver_Date