使用 WITH AS 后获取重复记录

Getting duplicate records after using WITH AS

我有三个 select 查询,它们按小时给出月份最后一天(当前、当前 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      | 

* 如果有任何其他最佳方法可以实现相同的目标,请分享。

您缺少 CURR, CURR_1, CURR_2 之间的联接。

联接应基于列 "Time"

所以您的 SELECT 查询应该是这样的:

SELECT
    *
FROM
    CURR JOIN
    CURR_1 USING("Time") JOIN
    CURR_2 USING("Time");

干杯!!

我想你想对月度结果进行透视,你可以使用条件聚合。

SELECT TO_CHAR(created_date, 'HH24') AS "Time"
    ,last_day(sysdate) AS m1
    ,last_day(add_months(sysdate, - 1)) m2
    ,last_day(add_months(sysdate, - 2)) m3
    ,count(CASE 
            WHEN created_date >= trunc(last_day(sysdate))
                THEN 1
            END) m1_count
    ,count(CASE 
            WHEN created_date >= trunc(last_day(add_months(sysdate, - 1)))
                THEN 1
            END) m2_count
    ,count(CASE 
            WHEN created_date >= trunc(last_day(add_months(sysdate, - 2)))
                THEN 1
            END) m3_count
FROM table1
GROUP BY TO_CHAR(created_date, 'HH24')
ORDER BY "Time";

注意:由于您尚未提供数据,因此未经测试query.Please尝试告诉我。