[英]Order by descending group by Max date, then order by single row in the group by date ascending using linq Method sintax
我有一張這樣的桌子
Id Date GroupId Text Column1 Column2 ...
1 2020-02-02 1 .... .... ...
2 2020-02-04 1 .... .... ...
3 2020-02-03 1 .... .... ...
4 2020-02-02 2 .... .... ...
5 2020-02-05 2 .... .... ...
我需要獲得這個結果:
Id Date GroupId Text Column1 Column2 ...
5 2020-02-05 2 .... .... ...
4 2020-02-02 2 .... .... ...
1 2020-02-02 1 .... .... ...
3 2020-02-03 1 .... .... ...
2 2020-02-04 1 .... .... ...
我解釋說我需要在第 2 組的所有行之前獲取,因為最大日期在第 2 組中......我需要按日期降序對組進行排序,但每個組都應按日期升序排序。
我也覺得很難用 sql 編寫它。 有人可以幫我嗎? 謝謝
編輯:這是我嘗試做的:
var result = messages.Select(m => new MyViewModel()
{
Id = m.Id,
Date = m.Date,
Text = m.Text,
GroupId = m.GroupId
}).GroupBy(d => d.GroupId)
.SelectMany(g => g)
.OrderByDescending(x => x.GroupId)
.ThenBy(x => x.Date);
但它不起作用
我建議創建一個具有GroupDate
屬性的中間結果。 在我的示例中,我使用的是C# 7.0 Tuples 。 如果您使用的是較舊的 C# 版本,您也可以使用匿名類型。
var result = messages
.GroupBy(m => m.GroupId) // Create Tuple ...
.Select(g => (Group: g, GroupDate: g.Max(m => m.Date))) // ... with group and group date.
.SelectMany(a => // Expand the group
a.Group.Select(m => // Create new tuple with group date and model.
(a.GroupDate,
Model: new MyViewModel() {
Id = m.Id,
Date = m.Date,
Text = m.Text,
GroupId = m.GroupId
})))
.OrderByDescending(x => x.GroupDate)
.ThenBy(x => x.Model.Date)
.Select(x => x.Model); // Extract the view model from the tuple.
結果:
Id = 2,日期 = 2020-02-02,GroupId = 2
Id = 2,日期 = 2020-02-05,GroupId = 2
Id = 1,日期 = 2020-02-02,GroupId = 1
Id = 1,日期 = 2020-02-03,GroupId = 1
Id = 1,日期 = 2020-02-04,GroupId = 1
元組示例:
var t = (X: 15, Name: "axis");
Print($"X = {t.X}, Name = {t.Name}");
元組屬性的名稱也可以像(a.GroupDate, Model: ...)
那樣推斷。 第一個屬性將自動稱為GroupDate
。 第二個被明確命名為Model
。
在 SQL 中,您可以使用窗口函數:
order by
max(date) over(partition by groupId),
case when max(date) over(partition by groupId) = max(date) over() then date end desc,
date
您想按最大日期對組進行排序。 然后在每個組內,按日期降序排列。
我會為以下order by
推薦這些鍵:
groupId
將每個組保持在一起(順序無關緊要)所以:
order by max(date) over (partition by groupId) desc,
groupId, -- put each group together
(case when date = max(date) over() then 1 else 2 end),
date
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.