我们第一次问这个问题。 我正在使用Oracle SQL并有一个包含列
的表RNUMBER为数字,PID为数字,VIEWDATE为日期,RENTED为char(1)
有多个行具有重复的RNUMBER但不同的VIEWDATE。我正在尝试使用将显示RNUMBER,PID,第一个VIEWDATE,最后一个VIEWDATE的查询。它应该与RNUMBERS匹配,最后一个VIEWDATE将有一个RENTED ='Y'。
这是我最接近的查询。
select a.*
from LabDataS13.lookedat a
inner join
(select RNumber
from LabDataS13.lookedat
where RENTED like 'N'
group by RNumber
having count(*) > 1) b
on a.RNumber = b.RNumber
where a.RENTED like 'Y'
order by a.RNUMBER
有点迷茫。任何帮助,将不胜感激。感谢
答案 0 :(得分:0)
由于你最后定义为'Y'所需要的只是第一条记录。要获得第一个,您可以使用Row_number。
WITH first
AS (SELECT Row_number()
over (
PARTITION BY rnumber
ORDER BY viewdate ) rn,
rnumber,
pid,
viewdate,
rented
FROM labdatas13.lookedat)
SELECT *
FROM labdatas13.lookedat last
inner join first
ON first.rnumber= last.rnumber
WHERE last.rented = 'Y'
AND first.rn = 1
如果出于某种原因你不能依赖租用的'Y'那么你只需要添加第二个ROW_NUMBER以另一种方式订购并使用WITH子句中的数据
WITH data
AS (SELECT Row_number()
over (
PARTITION BY rnumber
ORDER BY viewdate ) rn_first,
Row_number()
over (
PARTITION BY rnumber
ORDER BY viewdate desc ) rn_last,
rnumber,
pid,
viewdate,
rented
FROM labdatas13.lookedat)
SELECT *
FROM data first
inner join data lastg
ON first.rnumber= last.rnumber
WHERE
first.rn_first = 1
AND last.rn_last= 1
答案 1 :(得分:0)
期望每个rnumber有多个viewdates条目,每个rnumber的最后一个viewdate只有租用='Y'而其他的不是'Y'
select a.rnumber,a.pid,first_viewdate,last_viewdate from
(select rnumber,pid,viewdate as last_viewdate from table where rented='Y') a,
(select rnumber,pid,viewdate as first_viewdate from table where rowid in
(select min(rowid) from table group by rnumber) and rented !='Y') b
where a.rnumber=b.rnumber;