ITEM QBIN ISSUED ADDDATE LCKDATE
014342-XY 0022-F 2011-12-24 2007-08-09 2010-12-28
014342-XY 0030+B 2009-12-26 2009-01-13 1900-01-01
014342-XY 0030-B 2010-04-15 NULL 2010-12-28
014342-XY 0030-D 2011-07-20 2010-12-28 2011-07-20
从上表我想要最近的日期 结果将是这个
ITEM QBIN recentdate
014342XY 002-F 2011-12-24
答复中的一句话非常感谢
提前致谢
答案 0 :(得分:1)
编辑#2:
select t1.item,
t1.qbin,
src.maxdate as RecentDate
from yourtable t1
inner join
(
select max(maxdate) MaxDate
from
(
select
case
when issued >= adddate and issued >= lckdate then issued
when adddate >= issued and adddate >= lckdate then adddate
when lckdate >= issued and lckdate >= adddate then lckdate end MaxDate
from yourtable
) t2
) src
on t1.issued = src.maxdate
or t1.adddate = src.maxdate
or t1.lckdate = src.maxdate
在SQL Server中,您可以使用 row_number()
:
select item, qbin, issued as RecentDate
from
(
select *,
row_number() over(partition by item order by issued desc) rn
from yourtable
) src
where rn = 1
或者您可以使用子查询:
select t1.item,
t1.qbin,
t1.issued as RecentDate
from yourtable t1
inner join
(
select item, max(issued) issued
from yourtable
group by item
) t2
on t1.item = t2.item
and t1.issued = t2.issued
答案 1 :(得分:1)
with t1 as
(
select ITEM,QBin,ISSUED as d from T
union all
select ITEM,QBin,ADDDATE as d from T
union all
select ITEM,QBin,LCKDATE as d from T
)
select * from
(
select t1.*,
row_number() over(partition by item order by d desc) rn from T1
) t2
where rn=1
答案 2 :(得分:0)
SELECT
t.ITEM, QBIN, ISSUED, adddate, lckdate
FROM TABLE t INNER JOIN
(SELECT
item,
CASE
WHEN max_issued >= max_adddate AND max_issued >= max_lckDate THEN max_issued
WHEN max_adddate >= max_issued AND max_adddate >= max_lckDate THEN max_adddate
ELSE max_lckDate
END AS max_date,
CASE
WHEN max_issued >= max_adddate AND max_issued >= max_lckDate THEN 'i'
WHEN max_adddate >= max_issued AND max_adddate >= max_lckDate THEN 'a'
ELSE 'l'
END AS src
FROM
(SELECT
item,
MAX(issued) AS max_issued,
MAX(ADDDATE) AS max_adddate,
MAX(LCKDATE) AS max_lckdate
FROM
TABLE
GROUP BY
item
) m ) c ON t.item = c.item
where
(src = 'i' AND t.issued = m.max_issued) OR
(src = 'a' AND t.ADDDATE = m.max_adddate) OR
(src = 'l' AND t.LCKDATE = m.max_lckDate)