将两个表合并为一个输出SQL

时间:2012-11-24 06:58:12

标签: mysql sql

我有两个表,销售和费用

例如

销售:

sales_date       Amount
2012-11-01      12000.55
2012-11-03       2650.00
2012-11-03       2650.00
2012-11-03       2650.00
2012-11-07      12900.00
2012-11-07       2900.00

开支:

Expense Date     Amount
2012-11-03         40.00
2012-11-10        100.00
2012-11-10       1000.00
2012-11-11         10.00
2012-11-17        100.00

我需要SQL查询输出

Date              Sales        Expense
2012-11-01      12000.55
2012-11-03       7950.00          40.00
2012-11-07      15800.00
2012-11-10                      1100.00
2012-11-11                        10.00
2012-11-17                       100.00

3 个答案:

答案 0 :(得分:1)

使用UNION ALL的嵌套查询将为您提供所需内容;首先分别获取所有销售行和所有费用行,然后GROUP将它们划分为每个日期的公共行;

SELECT date, FLOOR(SUM(s)) AS sales, FLOOR(SUM(e)) AS expense
FROM
(
  SELECT sales_date  AS date, amount AS s, 0 AS e FROM sales
  UNION ALL     
  SELECT expensedate AS date, 0 AS s, amount AS e FROM expense
) AS individual_rows
GROUP BY date
ORDER BY date;

如果您不想要舍入({结果似乎表明您这样做了),可以省略FLOOR

SQLfiddle demo

答案 1 :(得分:0)

你需要的是一个完整的外部加入:

SELECT COALESCE(E.Date, S.Date) AS Date,
       SUM(S.Amount) AS Sales,
       SUM(E.Amount) AS Expenses
  FROM Expenses AS E
  FULL OUTER JOIN Sales AS S
    ON E.Date = S.Date
 GROUP BY COALESCE(E.Date, S.Date);

那是标准SQL;我们现在必须找出MySQL是否支持它。不幸的是,正如评论者所说,MySQL不支持FULL OUTER JOIN。

在这种情况下,您必须使用LEFT OUTER JOIN和RIGHT OUTER JOIN的UNION模拟FULL OUTER JOIN:

SELECT E.Date AS Date, SUM(S.Amount) AS Sales, SUM(E.Amount) AS Expenses
  FROM Expenses AS E
  LEFT OUTER JOIN Sales AS S
    ON E.Date = S.Date
 GROUP BY E.Date
UNION
SELECT S.Date AS Date, SUM(S.Amount) AS Sales, SUM(E.Amount) AS Expenses
  FROM Expenses AS E
 RIGHT OUTER JOIN Sales AS S
    ON E.Date = S.Date
 GROUP BY S.Date;

答案 2 :(得分:0)

您需要完整的外部联接。如果mysql不支持它,请查看here以获取可能的解决方法