1
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

高度赞赏的回复

提前致谢

4

3 回答 3

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 Fiddle

在 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

请参阅带有演示的 SQL Fiddle

或者您可以使用子查询:

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

请参阅带有演示的 SQL Fiddle

于 2012-12-07T18:13:30.600 回答
1

这是一个SQLFiddle 演示

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
于 2012-12-07T18:39:42.610 回答
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) 
于 2012-12-07T18:23:03.860 回答