我有两个SQL表,其中一个包含销售订单日期和当天的总数。然后,我有另一个表,其中包含发票日期和当天的总发票。这两个表上都有一些日期,根本没有记录。
我需要您的帮助才能将这两个表连接起来,并获取下图所示的每天的销售订单总额和发票总额。
答案 0 :(得分:4)
也许最简单的方法是汇总UNION ALL
示例
Select [Date] = OrderDate
,Sales = sum(Sales)
,Invoice = sum(Invoice)
From (
Select OrderDate
,Sales = sum(LovalValue)
,Invoice = cast(null as money)
From SalesOrd_HDR
Group By OrderDate
Union All
Select TransDate
,cast(null as money)
,sum(Amount)
From DR_Trans
WHERE TRANSTYPE = '1'
Group By TransDate
) A
Group By OrderDate
答案 1 :(得分:2)
您可以通过两个聚合子查询和一个FULL OUTER JOIN
来实现:
SELECT
COALESCE(ord.oday, inv.iday) AS date,
ord.ototal AS order_total,
inv.itotal AS invoice_total
FROM
(
SELECT
CAST(orderdate AS DATE) AS oday,
SUM(localvalue) AS ototal,
FROM dbo.SALESORD_HRD
GROUP BY CAST(orderdate As DATE)
) AS ord FULL OUTER JOIN (
SELECT
CAST(transdate AS DATE) iday,
SUM(amount) itotal,
FROM dbo.DR_TRANS
WHERE TRANSTYPE = '1'
GROUP BY CAST(transdate As DATE)
) AS inv
ON ord.oday = inv.iday