1

我有两张表,销售和费用

例如

销售量:

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
4

3 回答 3

1

带有 a 的嵌套查询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您不想四舍五入,可以省略 's (您的结果似乎表明您愿意)

SQLfiddle 演示

于 2012-11-24T07:19:59.293 回答
0

您需要的是 FULL OUTER JOIN:

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;
于 2012-11-24T07:03:26.113 回答
0

您需要一个完整的外部连接。如果 mysql 不支持它,请在此处查找可能的解决方法

于 2012-11-24T07:04:47.897 回答