我需要在我的项目中编写一个查询,我想在另一个表的每个日期范围(对于ORACLE数据库)总和一列。
TABLE1 - 每个日期都有预订的人数:
DT NO_OF_PAX
-------- ---------------
01-JAN-14 10
02-JAN-14 5
03-JAN-14 8
05-JAN-14 5
:
:
28-DEC-14 20
30-DEC-14 9
31-DEC-14 15
TABLE2 - 它有很多日期范围:
ST_DT END_DT
--------- ------------
01-JAN-14 31-JAN-14
01-FEB-14 28-FEB-14
12-JAN-14 15-FEB-14
:
:
01-NOV-14 20-NOV-14
01-DEC-14 31-DEC-14
现在我需要编写一个查询,它应该从TABLE1为TABLE2的每个日期范围显示SUM(NO_OF_PAX)。请告知我该怎么写。
由于两者都没有共同列,我不知道如何加入这两个表。我写道
SELECT SUM(TABLE1.NO_OF_PAX) FROM TABLE1, TABLE2
WHERE TABLE1.DT BETWEEN TABLE2.ST_DT AND TABLE2.END_DT
没有单组组功能失败。
答案 0 :(得分:0)
运行此并让我知道您的结果(测试)
SELECT A.ST_DT, A.END_DT, SUM(A.NO_OF_PAX) FROM
(
SELECT t2.*, t1.NO_OF_PAX
FROM Table1 t1,
Table2 t2
WHERE t1.DT BETWEEN t2.ST_DT AND t2.END_DT
) A
GROUP BY A.ST_DT, A.END_DT
答案 1 :(得分:0)
以这种方式试试
SELECT st_dt, end_dt, COALESCE(SUM(no_of_pax), 0) total
FROM Table2 t2 LEFT JOIN Table1 t1
ON t1.dt BETWEEN t2.st_dt AND end_dt
GROUP BY st_dt, end_dt
示例输出:
| ST_DT | END_DT | TOTAL | |-----------|------------|-------| | 01-JAN-14 | 31-JAN-14 | 28 | | 12-JAN-14 | 15-FEB-14 | 0 | | 01-FEB-14 | 28-FEB-14 | 0 | | 01-NOV-14 | 20-NOV-14 | 0 | | 01-DEC-14 | 31-DEC-14 | 44 |
这是 SQLFiddle 演示
答案 2 :(得分:0)
这是正确的SQL:
SELECT T2.ST_DT, T2.END_DT,
(
SELECT SUM(T1.NO_OF_PAX)
FROM TABLE1 T1
WHERE T1.DT BETWEEN T2.ST_DT AND T2.END_DT
) NO_OF_PAX
FROM TABLE2 T2
ORDER BY T2.ST_DT ASC
参见SQLFiddle http://sqlfiddle.com/#!4/2e9e9/1/0