问题描述
我有带有两列关键字和事件日期的“ ApplicationEventsSearch”表 我想查询一个以返回结果作为关键字,但由EventDate按升序排序的查询 我尝试了很多组合,但是都没有用
数据
Keyword EventDate
123457 2020-09-01
123457fdfdfdfd 2020-09-01
123457fdfdfdfd 2020-09-02
123457fdfdfdfd 2020-09-03
所需结果
1-123457fdfdfdfd,2-123457
以及到目前为止我已经尝试过的
SELECT
[Keyword],EventDate
FROM [NavaarDb-Dev].[dbo].[ApplicationEventsSearch]
group by Keyword,EventDate
order by EventDate
SELECT
distinct [Keyword],EventDate
order by EventDate
解决方法
在MIN
中只是MAX
或ORDER BY
之后的您吗?
SELECT Keyword
FROM dbo.YourTable
GROUP BY KeyWord
ORDER BY MAX(EventDate) ASC;
,
这回答了问题
数据
drop table if exists #tTEST;
go
select * INTO #tTEST from (values
('123457','2020-09-01'),('123457fdfdfdfd','2020-09-02'),'2020-09-03')) V(Keyword,EventDate);
查询
;with kw_cte as (select *,row_number() over (partition by Keyword order by EventDate desc) rn from #tTEST)
select
concat_ws('-',row_number() over (order by EventDate desc),Keyword) string
from kw_cte
where rn=1;
结果
string
1-123457fdfdfdfd
2-123457