如何找到最近的日期

时间:2015-04-10 00:15:13

标签: sql

数据:

id  |status| Date   | what_i_need
------------------------------- 
1   |C     |Jan-15  |Jan-15
1   |C     |Feb-15  |Feb-15
1   |D     |Mar-15  |Feb-15
1   |D     |Apr-15  |Feb-15
1   |C     |May-15  |May-15
1   |C     |Jun-15  |Jun-15
1   |D     |Jul-15  |Jun-15
1   |D     |Aug-15  |Jun-15

max date更改为status时,需要捕获D

我尝试了什么:

SELECT t.ID, t.Status, t.Date,
CASE
WHEN status = 'D' THEN d.last_current ELSE t.date END AS what_i_need
FROM table t
LEFT OUTER JOIN
(
SELECT id, MAX(date) as last_current
FROM table t
WHERE status = 'c'
GROUP BY id) d on d.id= t.id

顶部的错误是返回以下结果:

id  |status| Date   | what_i_need
---------------------------------- 
1   |C     |Jan-15  |  Jan-15
1   |C     |Feb-15  |Feb-15
1   |D     |Mar-15  |jun-15  <----This is wrong should be Feb 15
1   |D     |Apr-15  |jun-15  <----This is wrong should be Feb 15
1   |C     |May-15  |May-15
1   |C     |Jun-15  |Jun-15
1   |D     |Jul-15  |Jun-15
1   |D     |Aug-15  |Jun-15 

3 个答案:

答案 0 :(得分:1)

当状态不是'D'时,我会描述您需要的最新日期(包括当前日期)。这至少解释了最后一栏。

我会为此逻辑使用相关子查询:

select t.*,
       (select max(t2.date)
        from table t2
        where t2.date <= t.date and
              t2.status <> 'D'
       ) as what_i_need
from table t;

答案 1 :(得分:0)

假设Date是唯一的,您可以使用自联接和条件聚合来获取状态不是D的最后日期

select t.id, t.status, t.date,
max(case when t2.status <> 'D' then t2.date end) what_i_need
from table t
join table t2 on t2.date <= t.date
group by t.id, t.status, t.date

答案 2 :(得分:0)

如果您使用的是Oracle,SQL Server或PostgreSQL,则可以使用分析函数:

select id,
       status,
       dt,
       case when status <> 'D' then dt
         else lag(max_dt_grp, grp) over(order by dt)
          end as what_i_need
  from (select x.*,
               max(case when status <> 'D' then dt end) over(partition by id, grp) as max_dt_grp
          from (select x.*,
                       row_number() over(order by dt) -
                       row_number() over(partition by id, status order by dt) as grp
                  from tbl x) x) x
 order by dt

小提琴: http://sqlfiddle.com/#!4/63bce5/7/0

(我更改了你的字段名称以避免使用保留字)