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 
相關問題