[英]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 ![]() |
2022-08-30 ![]() |
0.061 ![]() |
0.063 ![]() |
0.06 ![]() |
0.06 ![]() |
ACR ![]() |
2022-08-31 ![]() |
0.066 ![]() |
0.07 ![]() |
0.066 ![]() |
0.07 ![]() |
NBI![]() |
2022-08-30 ![]() |
1.52 ![]() |
1.52 ![]() |
1.51 ![]() |
1.52 ![]() |
NBI![]() |
2022-08-31 ![]() |
1.51 ![]() |
1.52 ![]() |
1.505 ![]() |
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 ![]() |
2022-08-31 ![]() |
0.066 ![]() |
0.07 ![]() |
0.066 ![]() |
0.07 ![]() |
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.