多列的区别和顺序

时间:2017-11-04 10:13:36

标签: sql sql-server tsql sql-order-by row-number

这是我的查询结果;

query result

我正在尝试使用不同的多个顺序。也许我说不出来。但我首先按参数排序是" priority1"列和其次按参数排序是"点"有明显的Sid。所以;

对我来说最重要的一栏是" priorty1"

第二个最重要的专栏" Point" 但每一个" sid"将显示一次。

我想要什么?

  • 我希望Id为7,因为priorty1最大,其中ID为1509。
  • 我希望Id为9,因为Point是最大的,其中ID为1510.

enter image description here

3 个答案:

答案 0 :(得分:3)

在这里,您可以使用Row_number函数为结果集分配排名或Row_orders:

SELECT *
FROM
(
    SELECT ID,
           [Sid],
           [Point],
           [priority1],
           JoinDate,
           Title,
           Content,
           ROW_NUMBER() OVER(PARTITION BY [Sid] ORDER BY [priority1] desc, [Point] desc) AS RN
    FROM <your_resultset>
) a where a.RN = 1;

结果:

enter image description here

答案 1 :(得分:2)

您可以使用cte和row_number获得所需的结果,如下所示。

 WITH cte as
  (SELECT t1.*, ROW_NUMBER() over(PARTITION BY sid
                                  ORDER BY priority DESC, point DESC) AS rn
   FROM table1 t1)
SELECT id,
       sid,
       point,
       priority --- and other columns
FROM cte
WHERE rn = 1

<强>结果:

id  sid     point   priority
---------------------------
7   1509    10      3
9   1510    45      2

您可以查看演示 here

答案 2 :(得分:0)

SELECT Sid,
       MAX(Point) KEEP (DENSE_RANK FIRST ORDER BY (priority1, Point)) as top_point,
       MAX(priority1) KEEP (DENSE_RANK FIRST ORDER BY (priority1, Point)) as top_priority,
       ....
FROM (The query you have)
GROUP By Sid

在这里阅读更多内容 https://docs.oracle.com/cd/B19306_01/server.102/b14223/analysis.htm#DWHSG0205

我猜你的意思只是一个值,所以它是分组的基础。

更新

https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql

SELECT
  Sid, priority1, Point,
  row_number() over(partition by Sid order by priority1, Point) as roworder
FROM (the query) 
HAVING roworder=1 ;