搞了一天,脑袋搞晕了,简单SQL问题,向高手们请教下!现在需求是:
对于A表2011年之前的数据,取 B表中降序后的第一条记录,
对于A表2011年之后的数据,取 B表中升序后的第一条记录。我写的SQL如下,但是有点错误:丢失关键字。
望高手帮忙修改下,谢谢!select a.id,a.contract_create_date, rate.region_code, rate.rate, rate.plipmtno
from A a,
(select r.id, r.region_code, r.rate, r.plipmtno,
row_number() over(partition by r.region_code order by r.period_id desc) rn_desc,
row_number() over(partition by r.region_code order by r.period_id desc) rn_asc
from B r
) rate
where a.id = rate.id
and (case when a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') then
rn_desc = 1
else
rn_asc = 1
end rec
);
对于A表2011年之前的数据,取 B表中降序后的第一条记录,
对于A表2011年之后的数据,取 B表中升序后的第一条记录。我写的SQL如下,但是有点错误:丢失关键字。
望高手帮忙修改下,谢谢!select a.id,a.contract_create_date, rate.region_code, rate.rate, rate.plipmtno
from A a,
(select r.id, r.region_code, r.rate, r.plipmtno,
row_number() over(partition by r.region_code order by r.period_id desc) rn_desc,
row_number() over(partition by r.region_code order by r.period_id desc) rn_asc
from B r
) rate
where a.id = rate.id
and (case when a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') then
rn_desc = 1
else
rn_asc = 1
end rec
);
解决方案 »
- 求个sql查询
- delphi如何链接Oracle数据库?
- 表结构不同怎么取它们的交集
- Oracle数据库表存储数据的问题
- 数据库面试题目,请高手指点一下
- 一个SQL查询,不知道能不能得到
- about Error : ORA-01031 insufficicient privileges !
- internal 的密码是什么呀?
- 我在线!在P4 XP上装ORACLE8.16NT企业版,装不上点了SETUP没有反应听说要改一个文件名字或者是下一个补丁,是什么 啊谢谢了
- 数据库 java.sql.SQLRecoverableException没法从套接字读取更多的数据
- 如何获取最接近当前时间的记录?
- 数据字典中的视图在pl/sql developer 中能不能看?
SELECT a.id, a.contract_create_date, rate.region_code, rate.rate, rate.plipmtno
FROM A a,
(SELECT r.id,
r.region_code,
r.rate,
r.plipmtno,
row_number() over(PARTITION BY r.region_code ORDER BY r.period_id DESC) rn_desc,
row_number() over(PARTITION BY r.region_code ORDER BY r.period_id DESC) rn_asc
FROM B r) rate
WHERE a.id = rate.id AND
(b.rn_desc = (CASE
WHEN a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') THEN
1 ELSE 0 END) OR
b.rn_asc = (CASE
WHEN a.contract_create_date >= to_date('2011-01-01', 'yyyy-mm-dd') THEN
1 ELSE 0 END)
)
case中只是一个函数而已,能使用函的地方都可以使用case,和普通函数使用方式没有什么区别
(b.rn_desc =
(CASE WHEN a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd')
THEN 1
ELSE 0
END)
OR
b.rn_asc =
(CASE WHEN a.contract_create_date >= to_date('2011-01-01', 'yyyy-mm-dd')
THEN 1
ELSE 0
END)
)
这样才能在where条件中算判断条件的表达式
--你的试试
where a.id = rate.id
and (case when a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') then
rn_desc = 1
else
rn_asc = 1
end);
--2
where a.id = rate.id and
((a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') and rn_desc = 1)
or (a.contract_create_date>=to_date('2011-01-01', 'yyyy-mm-dd') and rn_asc = 1))--3
where a.id = rate.id and
(rn_desc=(case when a.contract_create_date < to_date('2011-01-01', 'yyyy-mm-dd') then 1 else 0 end)
or
rn_asc=(case when a.contract_create_date>=to_date('2011-01-01', 'yyyy-mm-dd') then 1 else 0 end))