【发布时间】:2019-08-06 06:08:25
【问题描述】:
我有三个选择查询,它们按小时对月份最后一天(当前、当前-1、当前-2)的记录进行计数。
我正在尝试使其三个输出并排出现的单个查询。
我使用with as 来完成这项工作。
问题是获得重复记录(近 2k 条记录),其中预期的最大行数为 24(因为每天 24 小时)。
查询:
with curr as
(
Select
last_day(add_months(trunc(sysdate, 'mm'), 0)),
TO_CHAR(created_date, 'HH24') as "Time",
count(1) as "Count"
from
table1
where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), 0)))
group by
TO_CHAR(created_date, 'HH24'),
last_day(add_months(trunc(sysdate, 'mm'), 0))
order by
TO_CHAR(cretd_date, 'HH24')
),
curr_1 as
(
Select
last_day(add_months(trunc(sysdate, 'mm'), -1)),
TO_CHAR(created_date, 'HH24') as "Time",
count(1) as "Count"
from
table1
where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), -1)))
group by
TO_CHAR(created_date, 'HH24'),
last_day(add_months(trunc(sysdate, 'mm'), -1))
order by
TO_CHAR(cretd_date, 'HH24')
),
curr_2 as
(
Select
last_day(add_months(trunc(sysdate, 'mm'), -2)),
TO_CHAR(created_date, 'HH24') as "Time",
count(1) as "Count"
from
table1
where cretd_date >= trunc(last_day(add_months(trunc(sysdate, 'mm'), -2)))
group by
TO_CHAR(created_date, 'HH24'),
last_day(add_months(trunc(sysdate, 'mm'), -2))
order by
TO_CHAR(cretd_date, 'HH24')
)
select * from curr, curr_1,curr_2;
实际输出:
2k repeated rows
预期输出:
max 24 rows
last_date | time | count | last_date | time_1 | count_1 | last_date | time_2| count_2 |
31-july-19 | 00 | 2 | 31-June-19 | 00 | 1 | 31-May-19 | 00 | 3 |
...
31-july-19 | 23 | 34 | 31-June-19 | 23 | 23 | 31-May-19 | 23 | 32 |
* 如果有任何其他最佳方法可以实现相同的效果,请分享。
【问题讨论】:
-
请说出投反对票的原因。考虑到你的观点,我会改进这个问题。
标签: sql oracle common-table-expression