[英]SQL Server: Two Level Sort (Order/Group By??)
Everyone:每个人:
I have the following code which produced the below table:我有以下代码生成下表:
SELECT DISTINCT a.[Date]
,a.[ID]
,a.[Account]
,a.[First_Last]
FROM [Table] AS a
WHERE [First_Last] = 1 OR
[First_Last] = (
SELECT MAX([First_Last])
FROM [Table] AS b
WHERE a.[ID] = b.[ID] AND a.[Account] = b.[Account]
)
ORDER BY [ID], [Account], [Date]
Date ID Account First_Last
10/31/2018 1111 45 1
1/29/2021 1111 45 4
9/29/2017 1111 753 1
9/28/2018 1111 753 2
9/29/2017 2222 481 1
1/31/2018 2222 481 2
10/31/2017 2222 488 1
1/31/2018 2222 488 2
11/30/2017 2222 582 1
1/31/2019 2222 582 3
2/28/2017 2222 621 1
2/28/2018 2222 621 2
6/30/2017 2222 1007 1
6/29/2018 2222 1007 2
But I need it to be ordered this way:但我需要以这种方式订购它:
Date ID Account First_Last
9/29/2017 1111 753 1
9/28/2018 1111 753 2
10/31/2018 1111 45 1
1/29/2021 1111 45 4
2/28/2017 2222 621 1
2/28/2018 2222 621 2
6/30/2017 2222 1007 1
6/29/2018 2222 1007 2
9/29/2017 2222 481 1
1/31/2018 2222 481 2
10/31/2017 2222 488 1
1/31/2018 2222 488 2
11/30/2017 2222 582 1
1/31/2019 2222 582 3
Notice that the table I need is not sorted by Account
.请注意,我需要的表没有按
Account
排序。 It is sorted by Date for each ID
- Account
combination.它按每个
ID
- Account
组合的日期排序。 For example, for ID = 1111, Account 753 comes before Account 45 because 753's first date is 9/29/2017 and 45's first date is 10/31/2018.例如,对于 ID = 1111,帐户 753 位于帐户 45 之前,因为 753 的第一个日期是 2017 年 9 月 29 日,而 45 的第一个日期是 2018 年 10 月 31 日。 Since I do not want
Account
to be sorted, I tried to remove Account
from the ORDER BY
, but that put the Account
numbers in random lines because of Date
instead of grouping them together.由于我不想对
Account
进行排序,因此我尝试从ORDER BY
中删除Account
,但是由于Date
而不是将它们组合在一起,因此将Account
编号放在随机行中。
What am I missing?我错过了什么?
Thank you.谢谢你。
You can use window function to find the "first date" by ID
and Account
.您可以使用 window function 通过
ID
和Account
查找“第一个日期”。
order by ID,
min([Date]) over(partition by ID, Account),
[Date]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.