按两列排序和排序 [英] Sorting and ordering by two columns

查看:35
本文介绍了按两列排序和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,它返回这样的结果集:

I have a query which returns a result set like this:

Proj  |  release  |  releaseDt
1     |   2       |  1/2/2013
1     |   1       |  4/5/2012
2     |   1       |  [null]
3     |   1       |  22/2/2013
1     |   3       |  [null]
3     |   2       |  [null]

我需要按 releaseDt 对其进行排序,但我需要将那个 Proj 的所有记录放在一起.

I need to sort this by releaseDt, but I need to have all the records for that Proj together.

排序后的结果应该是这样的:

After sorting, the result should be something like this:

Proj | release |   releaseDt
1    |  2      |   1/2/2013
1    |  1      |   4/5/2012
1    |  3      |   [null]
3    |  1      |   22/2/2013
3    |  2      |   [null]
2    |  1      |   [null]

如何使用 SQL Server 执行此操作?

How can I do this with SQL Server?

推荐答案

您希望先按项目的最早发布日期排序,然后再按项目内的发布日期排序.

You want to sort by the earliest release date for a project and then by the release date within a project.

您可以使用窗口函数获取最早的日期,然后将其用于排序:

You can get the earliest date using a window function, and then use that for sorting:

select t.Proj, t.release, t.releaseDt
from (select t.*, min(releasedt) over (partition by proj) as minrdt
      from t
     ) t
order by t.minrdt, t.proj, t.releaseDt

这篇关于按两列排序和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆