简体   繁体   English

SQL Server中的分组依据,派生表中的排序依据和行号

[英]Group by, Order by in derived table and Row Number together in SQL Server

I want that first data should be sorted using id desc , then grouped by and then row number finally. 我希望第一个数据应该使用id desc进行排序,然后按分组,最后是行号。 I am going to use the table in data-tables pagination. 我将在数据表分页中使用该表。

I want to display Lastname and Designation of employee according to their emp id descending, means first 10 in data tables are the one who joined recently. 我想显示LastnameDesignation根据自己的EMP ID降员工,首先意味着10数据表是谁最近加入了一个。

Below is my query but SQL Server does not allow order by in a derived table but I cannot put order by in outer last table because that will disturb my row id number and correct data will not be displayed in pagination. 下面是我的查询,但是SQL Server不允许在派生表中进行排序,但是我不能在外部最后一个表中进行排序,因为这会干扰我的行ID号,并且分页中不会显示正确的数据。

SELECT 
    lastname, designation, 
    row_number() OVER (ORDER BY @@rowcount) AS RowNumber
FROM 
   (SELECT 
        MAX (id), lastname, designation
    FROM employees
    GROUP BY lastname, designation
    ORDER BY MAX(id) DESC) r WHERE r.RowNumber between 1 and 2;

Output: 输出:

ID  LastName    Designation
----------------------------
1 | ABC Java  |  Developer
2 | EFG Dot   |  Developer
3 | HIJ PHP   |  Developer
4 | PQR Sql   |  Developer

Required output but without ID 必填输出,但没有ID

ID  LastName    Designation        RowNumber
-----------------------------------------------
 4 |    PQR Sql   |  Developer       |    1
 3 |    HIJ PHP   |  Developer       |    2

The query shown above is not working in SQL Server 上面显示的查询在SQL Server中不起作用

Thanks 谢谢

Is this what you want? 这是你想要的吗?

SELECT lastname, designation,
       row_number() over (order by max(id) desc) as rownum
FROM employees
GROUP BY lastname, designation
ORDER BY MAX(id) DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM