我想从union列中获取最后一个请求日期。 我有这段代码显示最后一个请求日期:
;with cte
as
(
select
[Date], [Badge id], Name, Reason, [Item1] item,
row_number() over (partition by [Badge id], [Item1] order by getdate()) rn
from tbl_Request2
where [Item1] Is Not null
union
select
[Date], [Badge id], Name, Reason,[Item2] item,
row_number() over (partition by [Badge id], [Item2] order by getdate()) rn
from tbl_Request2 where [Item2] is not null union
)
Select
T.[Badge ID], T.Name, T.Item, T.Reason, T. [Date] as [Current Request],
ISNULL((Select top 1 [Date]
from CTE
where
CTE.[Badge Id]=T.[Badge Id] and
CTE.[Item] = T.item and
CTE. [Date] < T. [Date]),T. [Date]) as [Last Requested]
From CTE T
order by [Badge ID]
它会显示最后一条记录,但不会显示预期的记录。它显示,例如:
ID 01 001 request item1 on 12/05/2014那么
ID 001再次请求2014年1月13日的第1项;它显示最后请求的12/05/2014;然后
ID 001在14/05/2014再次请求Item1;它显示最后请求的12/05/2014; - &GT;这是错误 我希望它显示最后一个请求13/05/2014
预期表格:
ID | Items | Date | Last Request Date
001 | Item1 | 12/05/2014 | 12/05/2014 --> lets say this is the first request of ID001
002 | Item2 | 25/04/2014 | 20/05/2014
001 | Item1 | 13/05/2014 | 12/05/2014 --> It display the date of first requested
001 | Item1 | 14/05/2014 | 13/05/2014 --> display the second request date
您对此错误有任何建议吗? 很抱歉再次发布。我昨天已经问了这个问题,但它仍有一些错误。
谢谢你的进步......
答案 0 :(得分:0)
这有点令人尴尬。我问了一个问题并自己回答。我只是意识到代码中缺少的东西。我只需删除前1并在我的代码上添加max(date)。对不起,问一些我错了。
;with cte
as
(
select
[Date], [Badge id], Name, Reason, [Item1] item,
row_number() over (partition by [Badge id], [Item1] order by getdate()) rn
from tbl_Request2
where [Item1] Is Not null
union
select
[Date], [Badge id], Name, Reason,[Item2] item,
row_number() over (partition by [Badge id], [Item2] order by getdate()) rn
from tbl_Request2 where [Item2] is not null union
)
Select
T.[Badge ID], T.Name, T.Item, T.Reason, T. [Date] as [Current Request],
ISNULL((Select max[Date] as [date]
from CTE
where
CTE.[Badge Id]=T.[Badge Id] and
CTE.[Item] = T.item and
CTE. [Date] < T. [Date]),T. [Date]) as [Last Requested]
From CTE T
order by [Badge ID]