SQL优雅:可以这样子选择来避免?

问题描述 投票:0回答:1

我有一个SQL语句,其中子查询的where子句是非常相似的地方外克劳斯。这让我不知道是否有表达出来一个更清洁的方式。

该数据每月接收更新,每行数据得到,当它出现开始日期和结束日期,当它不再出现。这既可以不再出现由于数据完全消失或改变数据在所有的行的行。任何给定的ID可以具有1个或多个行数据。我的内部的选择的发现所有的ID,其中的任何行的最近更改/被除去并且外选择找到与那些当前或最近改变ID的所有行/被删除。这在Netezza公司运行。

select A.*, Case when current='Y' then (case when start_date='20190101' then 'NEW' else 'Is' end) else 'Gone' end as status
from DataSource A
join (
select A.ID from IDsOfInterest A join DataSource B on A.ID=B.ID
where (current='Y' and start_date='20190101') or end_date='20190101'
group by a.id
) B on A.ID=B.ID
where (current='Y') or end_date='20190101'

per comment, sample data. Assume ID 1 exists in table IDsOfInterest:
Table DataSource:
ID, current, start_date, end_date, data, note
1, 'N', 20180101, 20180201, A, Disappears
1, 'N', 20180101, 20180201, B, Changes
1, 'Y', 20180201, 99991231, B, Changed
1, 'N', 20180101, 20190101, C, Recently Gone
1, 'Y', 20180101, 99991231, D, Always there
1, 'N', 20180101, 20190101, E, Recently Changes
1, 'Y', 20190101, 99991231, E, Recently Changed

Query results:
1, 'Y', 20180201, 99991231, B, Changed, Is
1, 'N', 20180101, 20190101, C, Recently Gone, Gone
1, 'Y', 20180101, 99991231, D, Always there, Is
1, 'N', 20180101, 20190101, E, Recently Changes, Gone
1, 'Y', 20190101, 99991231, E, Recently Changed, NEW
sql netezza
1个回答
0
投票

如果你使用with你可以用where子句中的过滤器一次查询数据

该代码是更清洁,因为在数据源表而不是两遍你正在读一次,你会得到一个性能优势。

with A as (
  select * from DataSource 
   where (current='Y' and start_date='20190101') or end_date='20190101'))
select A.*, Case when current='Y' then (case when start_date='20190101' 
               then 'NEW' else 'Is' end) else 'Gone' end as status
  from A
  join (
select I.ID from IDsOfInterest I join A on I.ID=A.ID
 group by a.id 
) B on A.ID=B.ID
where current='Y' or end_date='20190101'

我们也可以将您的加入让ID添加到过滤器,这将是比快加入

with A as (
  select * from DataSource 
   where (current='Y' and start_date='20190101') or end_date='20190101'))
select A.*, Case when current='Y' then (case when start_date='20190101' 
               then 'NEW' else 'Is' end) else 'Gone' end as status
 from A
where current='Y' or end_date='20190101'
  and ID in (select distinct I.ID from IDsOfInterest I join A on I.ID=A.ID) 

请让我知道这可不可以帮你

© www.soinside.com 2019 - 2024. All rights reserved.