SQL Server の 1 つの列でグループ化し、集計関数にも GROUP BY 句にも含まれていない別の列で並べ替える

okwaves2024-01-25  211

「ApplicationEventsSearch」テーブルがあります。キーワードとイベント日付の 2 列 結果を個別のキーワードとして返すクエリが必要ですが、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
  FROM [NavaarDb-Dev].[dbo].[ApplicationEventsSearch]
  group by Keyword,EventDate
 order by EventDate


------------------------

ORDER BY で求めているのは MIN または MAX だけではありませんか?

SELECT Keyword
FROM dbo.YourTable
GROUP BY KeyWord
ORDER BY MAX(EventDate) ASC;

0



------------------------

これが質問の答えです

データ

drop table if exists #tTEST;
go
select * INTO #tTEST from (values 
('123457', '2020-09-01'),
('123457fdfdfdfd', '2020-09-01'),
('123457fdfdfdfd', '2020-09-02'),
('123457fdfdfdfd', '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

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。