对多列进行区分和排序

Distinct and order by for multiple columns

这是我的查询结果;

我正在尝试使用不同的和多个排序依据。也许我说不出来。但是我首先按参数排序是 "priority1" 列,其次按参数排序是 "point" With Distinct Sid。所以;

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

第二重要的栏目"Point" 但是每个 "sid" 都会显示一次。

我想要什么?

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 ;

在这里,您可以使用 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;

结果:

您可以使用 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