简体   繁体   English

多个 SELECTS 和一个 CTE 表

[英]Multiple SELECTS and a CTE table

I have this statement which returns values for the dates that exist in the table, the cte then just fills in the half hourly intervals.我有这个语句,它返回表中存在的日期的值,然后 cte 只填充半小时间隔。

    with cte (reading_date) as (
    select date '2020-11-17' from dual
    union all
    select reading_date + interval '30' minute 
    from cte 
    where reading_date + interval '30' minute < date '2020-11-19'
)
select c.reading_date, d.reading_value
from cte c
left join dcm_reading d on d.reading_date = c.reading_date
order by c.reading_date

However, later on I needed to use A SELECT within a SELECT like this:但是,后来我需要在 SELECT 中使用 A SELECT,如下所示:

   SELECT serial_number,
register,
reading_date,
reading_value,,
ABS(A_plus)
FROM
(
SELECT
serial_number,
register,
TO_DATE(reading_date, 'DD-MON-YYYY HH24:MI:SS') AS reading_date,
reading_value,
LAG(reading_value,1, 0) OVER(ORDER BY reading_date) AS previous_read,
LAG(reading_value, 1, 0) OVER (ORDER BY reading_date) - reading_value AS A_plus,
reading_id
FROM DCM_READING
WHERE device_id = 'KXTE4501'
AND device_type = 'E'
AND serial_number = 'A171804699'
AND reading_date BETWEEN TO_DATE('17-NOV-2019' || ' 000000', 'DD-MON-YYYY HH24MISS') AND  TO_DATE('19-NOV-2019'   || ' 235959', 'DD-MON-YYYY HH24MISS')
ORDER BY reading_date)
ORDER BY serial_number, reading_date;

For extra information:如需额外信息:

I am selecting data from a table that exists, and using lag function to work out difference in reading_value from previous record.我正在从存在的表中选择数据,并使用滞后 function 来计算 read_value 与先前记录的差异。 However, later on I needed to insert dummy data where there are missing half hour reads.但是,后来我需要在缺少半小时读取的地方插入虚拟数据。 The CTE table brings back a list of all half hour intervals between the two dates I am querying on. CTE 表带回了我查询的两个日期之间所有半小时间隔的列表。

ultimately I want to get a result that has all the reading_dates in half hour, the reading_value (if there is one) and then difference between the reading_values that do exist.最终我想得到一个结果,其中包含半小时内的所有读数日期、读数值(如果有的话)以及确实存在的读数值之间的差异。 For the half hourly reads that don't have data returned from table DCM_READING I want to just return NULL.对于没有从表 DCM_READING 返回数据的半小时读取,我只想返回 NULL。

Is it possible to use a CTE table with multiple selects?是否可以使用具有多个选择的 CTE 表?

Not sure what you would like to achieve, but you can have multiple CTEs or even nest them:不确定您想要实现什么,但您可以拥有多个 CTE,甚至可以嵌套它们:

with 

cte_1 as
(
    select username
    from dba_users
    where oracle_maintained = 'N'
),

cte_2 as
(
    select owner, round(sum(bytes)/1024/1024) as megabytes
    from dba_segments
    group by owner
),

cte_3 as
(
    select username, megabytes
    from cte_1
    join cte_2 on cte_1.username = cte_2.owner
)

select *
from cte_3
order by username;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM