我有一张桌子:
| id_record | code | date |
---------------------------------------------
| 12395 | 90 | 23-11-2016 |
| 18733 | 90 | 05-10-2016 |
| 10084 | 9201 | 13-10-2016 |
| 10400 | 9000 | 23-11-2016 |
输入参数@date
(日期时间)。 @date='24-11-2016'
。我想收到:
| id_record | code | date |
---------------------------------------------
| 12395 | 90 | 23-11-2016 |
| 10084 | 9201 | 13-10-2016 |
| 10400 | 9000 | 23-11-2016 |
即我想获得max(date)<=@date
和distinct code
值的每个代码。哪个要求我必须使用?
答案 0 :(得分:0)
CREATE TABLE Table3
(id_record int, code int, date varchar(10))
;
INSERT INTO Table3
VALUES
(12395, 90, '23-11-2016'),
(18733, 90, '05-10-2016'),
(10084, 9201, '13-10-2016'),
(10400, 9000, '23-11-2016')
with cte as (
select *,row_number() over(partition by code order by date desc) as rn from Table3
)
select id_record,code,date from cte where rn=1 and date<='24-11-2016'