如何在两个日期之间的两个不同表中SUM两个不同的列

时间:2016-03-14 20:07:23

标签: sql-server sql-server-2008 sql-server-2005 sql-server-2012

以下是我的询问:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

document.getElementsByClassName("Filler")