我在Oracle中有一個SQL表。我必須連接2個表(一個表有ID和其他資料,第二個表每行有ID和日期,第二個表顯示在下面),但不希望從第二個表中得到連接的資料,而只希望得到標簽(1或0,基于搜索ID有一個日期在21/08/01到21/08/31的條件)。
Table 2
# ID Date
# 1 21/08/01
# 2 21/07/02
# 3 21/08/24
# 4 21/08/02
# 5 21/06/03
# 6 21/08/05
# 7 21/08/26 # 6 21/08/05
# 8 21/08/05
我想要的輸出應該是:
Table 1
# ID Date Other data
# 1 1 ....
# 2 0 ....
# 3 1 ....
# 4 1 ....
# 5 0 ....
# 6 1 ....
# 7 1 ....
# 8 1 ....
有人能幫忙嗎?
uj5u.com熱心網友回復:
對我來說,看起來像CASE:
with temp_2 as
(select b.id。
b.姓名。
b.地址。
b.date_column。
rank() over (partition byb. id order by b.date_column desc) rnk
from table_2 b
)
選擇
a.id,
a.some_other_column。
--
case when b. date_column between date '2021-08-01' and date '2021-08-31' then 1
else 0
end as標簽
from table_1 a left join temp_2 b on a. id = b.id and b.rnk = 1
uj5u.com熱心網友回復:
如果在table2中只有一個id,你可以使用left join:
select t`.*,
(case when t2. date is null then 0 else 1 end) as flag
from table1 t1 left join
table2 t2
on t2.id= t1.id and
t2.date between date '2021-08-01' and date '2021-08-31。
在table2中,一個更通用的解決方案是exists:
select t.*,
(case when exists (select 1)
from table2 t2
where t2.id = t1.id and.
t2. 日期 between date '2021-08- 01' and date '2021-08-31')
)
then 1 else 0 >。
end) as flag
from table1 t1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/325001.html
標籤:
上一篇:如何在保留檔案名其余部分的同時,用bash將數字的第一個實體置零?
下一篇:甲骨文按登錄日期獲取玩家數量
