0

之间下面是我的查询:如何总结两个不同的列在两个不同的表中两个日期

select sum(tableA.value)+sum(tableB.value1)) from tableA,tableB where tableA.data between '2016-01-21' and '2016-03-09' and tableB.date2 between '2016-01-21' and '2016-03-09'

但结果是错误的,当行数是不同的。 实施例tableA.value = 2个tableB的值= 3和5的结果= 12

这是错误的。结果应该是10

回答

0
;with sumA as (
    select sum(tableA.value) value from tableA 
    where tableA.data between '2016-01-21' and '2016-03-09' 
), sumB as (
    select sum(tableB.value) value from tableB 
    where tableB.date2 between '2016-01-21' and '2016-03-09' 
) 
select a.Value + b.Value from sumA, sumB; 
0

请尝试以下查询

SELECT 
    SUM(A.value) OVER (PARTITION BY A.date order by A.date) + 
    SUM(B.value) OVER (PARTITION BY B.date order by B.date) 
FROM 
(select value, date from tableA where date between '2016-01-21' and '2016-03-09')A --2, d1 
CROSS JOIN 
(select value, date from tableB where date between '2016-01-21' and '2016-03-09')B --3,d2 and 5,d3 
--Result of CROSS JOIN is below 
--2,d1,3,d2 
--2,d1,5,d3 
-- which gives result as 
--2+8=10 
相关问题