在SQL中以ID,Month级别准备数据

时间:2018-03-04 04:45:20

标签: sql sql-server-2012

我有一张类似这样的表:

ID  Date
1   10/04/2015
1   28/04/2015
1   14/07/2015
1   30/07/2015
1   30/08/2015
2   10/04/2016
2   28/04/2016
2   14/05/2016
2   30/05/2016

但我正努力实现:

ID  Date
1   28/04/2015
1   30/07/2015
1   30/08/2015
2   28/04/2016
2   30/05/2016
你能帮我吗?

2 个答案:

答案 0 :(得分:0)

我并没有真正得到预期结果的逻辑,但下面的查询会有效。

SELECT *
FROM yourTable 
WHERE DAY([Date])>=28;

请参阅How to get Day, Month and Year Part from DateTime in Sql Server

答案 1 :(得分:0)

试试这个:

select * from (
    select id,
           [Date],
           row_number() over (partition by id, datepart(month, [date]) order by [Date] desc) [rn]
    from (
    select id, 
           --date convrsion, 103 - British/French - your style
           convert(date, [date], 103) [Date]
    from @MyTable
    ) a
) b where rn = 1