Dav*_*vid 5 sql t-sql group-by
假设我有一个如下所示的数据库表:
ID name salary start_date city region
----------- ---------- ----------- ----------------------- ---------- ------
1 Jason 40420 1994-02-01 00:00:00.000 New York W
2 Robert 14420 1995-01-02 00:00:00.000 Vancouver N
3 Celia 24020 1996-12-03 00:00:00.000 Toronto W
4 Linda 40620 1997-11-04 00:00:00.000 New York N
5 David 80026 1998-10-05 00:00:00.000 Vancouver W
6 James 70060 1999-09-06 00:00:00.000 Toronto N
7 Alison 90620 2000-08-07 00:00:00.000 New York W
8 Chris 26020 2001-07-08 00:00:00.000 Vancouver N
9 Mary 60020 2002-06-09 00:00:00.000 Toronto W
Run Code Online (Sandbox Code Playgroud)
是否可以通过start_date降序对其进行排序,然后通过最新的start_date对每个城市组进行排序?例如:
ID name salary start_date city region
----------- ---------- ----------- ----------------------- ---------- ------
9 Mary 60020 2002-06-09 00:00:00.000 Toronto W
6 James 70060 1999-09-06 00:00:00.000 Toronto N
3 Celia 24020 1996-12-03 00:00:00.000 Toronto W
8 Chris 26020 2001-07-08 00:00:00.000 Vancouver N
5 David 80026 1998-10-05 00:00:00.000 Vancouver W
2 Robert 14420 1995-01-02 00:00:00.000 Vancouver N
7 Alison 90620 2000-08-07 00:00:00.000 New York W
4 Linda 40620 1997-11-04 00:00:00.000 New York N
1 Jason 40420 1994-02-01 00:00:00.000 New York W
Run Code Online (Sandbox Code Playgroud)
谢谢您的回复.
在SQL Server 2005或更新版本可能是这样的:
select
*
from
(select *,max(start_date) over(partition by city) max_date from tablename) alias
order by max_date desc, start_date desc
Run Code Online (Sandbox Code Playgroud)
尝试这个:
SELECT *
FROM
(
SELECT
*,
(SELECT MAX(start_date) FROM cities c2 WHERE c1.city = c2.city) AS latest_start_date
FROM cities c1
)
ORDER BY latest_start_date DESC, start_date DESC
Run Code Online (Sandbox Code Playgroud)
内部查询会给你这样的结果:
ID name salary start_date city region lastest_start_date
----------- ---------- ----------- ----------------------- ---------- ------ -------------------
1 Jason 40420 1994-02-01 00:00:00.000 New York W 2000-08-07 00:00:00.000
2 Robert 14420 1995-01-02 00:00:00.000 Vancouver N 2001-07-08 00:00:00.000
3 Celia 24020 1996-12-03 00:00:00.000 Toronto W 2002-06-09 00:00:00.000
4 Linda 40620 1997-11-04 00:00:00.000 New York N 2000-08-07 00:00:00.000
5 David 80026 1998-10-05 00:00:00.000 Vancouver W 2001-07-08 00:00:00.000
6 James 70060 1999-09-06 00:00:00.000 Toronto N 2002-06-09 00:00:00.000
7 Alison 90620 2000-08-07 00:00:00.000 New York W 2000-08-07 00:00:00.000
8 Chris 26020 2001-07-08 00:00:00.000 Vancouver N 2001-07-08 00:00:00.000
9 Mary 60020 2002-06-09 00:00:00.000 Toronto W 2002-06-09 00:00:00.000
Run Code Online (Sandbox Code Playgroud)