我有两个表,例如
其中 point 和 date 是主键。
我需要在任何给定日期找出总收入inc
和结果out
。
我的回答
WITH all_date AS
(SELECT point, date FROM income
UNION
SELECT point, date FROM outcome)
SELECT a.point, a.date, SUM(inc), SUM(out)
FROM all_date a LEFT JOIN income i ON i.point=a.point AND i.date=d.date
LEFT JOIN outcome o ON o.point=a.point AND o.date=a.date
GROUP BY a.point, a.date
但是我得错了结果。因为all_date LEFT JOIN income
尝试与LEFT JOIN
进行outcome
重复income
中的某些行,因此会弄乱最终的SUM
。
基本上我想LEFT JOIN
第三个表格outcome
all_date
而不是 all_date LEFT JOIN income
。有关进一步说明,请参阅http://www.sql-ex.ru/learn_exercises.php的第30号课程
答案 0 :(得分:4)
为什么不先加入呢?
甚至更好,只需做一个完整的外部联接:
Select coalesce(o.point, i.point) point,
coalesce(o.Date, i.date) date
From income i full join outcome o
on o.point=i.point
and o.date=i.date
group by coalesce(o.point, i.point),
coalesce(o.Date, i.date)
并且,由于您实际上并未使用任何聚合函数,因此也可以使用distinct:
Select distinct
coalesce(o.point, i.point) point,
coalesce(o.Date, i.date) date
From income i full join outcome o
on o.point=i.point
and o.date=i.date
道歉,我不是MySQL人,也没有意识到MySQL没有Full Join语法。但有一个解决方法。请看以下链接:
基本上你需要一个联盟,(接近你正在做的事情,实际上)
select point, date
from income i
left join outcome o
on o.point=i.point
and o.date=i.date
UNION -- <-- leave out the ALL to eliminate duplicates
select point, date
from outcome o
right join income i
on i.point=o.point
and i.date=o.date
答案 1 :(得分:0)
我不知道在这里使用表表达式的目的是什么,你可以在这里使用一个连接来获得结果:
SELECT i.point, i.date, SUM(inc), SUM(out)
FROM income i
LEFT JOIN outcome o
ON o.point=i.point AND o.date=i.date
GROUP BY i.point, i.date
答案 2 :(得分:0)
MS-SQL sp解决您的问题:
CREATE PROCEDURE dototals
@date DATETIME
AS
BEGIN
SELECT point,SUM(ISNULL(inc,0)) as inc into #tmp_i FROM Income WHERE date =@date GROUP BY point
SELECT point,SUM(ISNULL(out,0)) as out into #tmp_d FROM Outcome WHERE date =@date GROUP BY point
SELECT DISTINCT point into #tmp_p FROM
(SELECT point FROM #tmp_i
UNION ALL
SELECT point FROM #tmp_o)
SELECT @date as date, t1.point as point, t2.out as outcome,t3.inc as income
FROM #tmp_p as t1
LEFT JOIN #tmp_o as t2 on t1.point=t2.point
LEFT JOIN #tmp_i as t3 on t1.point=t3.point
END
答案 3 :(得分:0)
这是我在MSSQL中的最终解决方案。但我希望COALESCE
使用FULL JOIN
效果最佳。
WITH all_date AS
(SELECT point, date FROM income
UNION
SELECT point, date FROM outcome)
SELECT a.point, a.date,
(SELECT SUM(o.out) FROM outcome o WHERE o.point=a.point AND o.date=a.date) AS outcome,
(SELECT SUM(i.inc) FROM income i WHERE i.point=a.point AND i.date=a.date) AS income
FROM all_date a