1

我有 2 张桌子:

  • 表 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 持空白。我敢肯定,对于外面的人来说,这是一个明智的选择!

提前致谢!K。

4

3 回答 3

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-syntax 并合并两个列,例如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
于 2013-06-13T21:33:13.257 回答
1

假设您使用 MySQL。您可以使用JOINs 来组合具有共同值的列:

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;

在此处查看演示

如果您的数据库支持完全外部联接(例如 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;
于 2013-06-13T19:19:16.930 回答
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
于 2013-06-13T19:20:07.903 回答