简体   繁体   English

如何从不同日期查询不同列中的两个值?

[英]How to query two values in different columns from different dates?

I'm trying to query a daily_price table by the following logic:我正在尝试通过以下逻辑查询daily_price表:

today's close > today's open and today's close > yesterdays high今日收盘 > 今日开盘今日收盘 > 昨日高点

The desired output is returning all rows from today that meet the criteria.所需的 output 将返回从今天起满足条件的所有行。 With the below example, and assuming today is 2022-08-31, the query would return ACR but not NBI because the logic matches (ie 2022-08-31 close > 2022-08-31 open and 2022-08-31 close > 2022-08-30 high).对于下面的示例,假设今天是 2022-08-31,查询将返回 ACR 但不返回 NBI,因为逻辑匹配(即 2022-08-31 关闭 > 2022-08-31 打开2022-08-31 关闭 > 2022-08-30 高)。

daily_price example: daily_price示例:

symbol象征 date日期 open打开 high高的 low低的 close
ACR ACR 2022-08-30 2022-08-30 0.061 0.061 0.063 0.063 0.06 0.06 0.06 0.06
ACR ACR 2022-08-31 2022-08-31 0.066 0.066 0.07 0.07 0.066 0.066 0.07 0.07
NBI北向北调 2022-08-30 2022-08-30 1.52 1.52 1.52 1.52 1.51 1.51 1.52 1.52
NBI北向北调 2022-08-31 2022-08-31 1.51 1.51 1.52 1.52 1.505 1.505 1.515 1.515

I tried this query with no luck:我试过这个查询没有运气:

SELECT * 
FROM daily_price 
WHERE close > open
AND date = '2022-08-31' 
AND (SELECT close FROM daily_price WHERE date = '2022-08-31') > (SELECT high FROM daily_price WHERE date = '2022-08-30')

I'm using lag to compare today's close with yesterday's high and filtering by date .我使用lag来比较今天的收盘价和昨天的高点并按date过滤。

select  symbol  
       ,date    
       ,open    
       ,high    
       ,low 
       ,close
from    (
        select *
              ,lag(high)    over (partition by symbol order by date)      as pre
        from   t
        ) t

where   close > pre 
  and   close > open 
  and   date = '2022-08-31'
symbol象征 date日期 open打开 high高的 low低的 close
ACR ACR 2022-08-31 2022-08-31 0.066 0.066 0.07 0.07 0.066 0.066 0.07 0.07

Fiddle 小提琴

You may use Exists with a correlated subquery as the following:您可以将Exists与相关子查询一起使用,如下所示:

Select T.symbol, T.date_, T.open, T.high, T.low, T.close 
From daily_price T
Where T.close > T.open And
Exists (Select 1 From daily_price D 
        Where D.symbol=T.symbol And 
              D.date_=Date(T.date_, '-1 day') And 
              D.high < T.close)

See a demo db<>fiddle .查看演示db<>fiddle

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

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