SQL选择何时表包含特定功能的几个相同记录

时间:2016-11-24 07:24:04

标签: sql-server sql-server-2000

我有一张桌子:

|    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)<=@datedistinct code值的每个代码。哪个要求我必须使用?

1 个答案:

答案 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'