简体   繁体   English

如何为SQL Server中的每个分区选择最大行数

[英]How to select max rownumber for each partition in SQL Server

Can anybody tell me how to select the max row number for each partition in SQL Server using CTE. 谁能告诉我如何使用CTE为SQL Server中的每个分区选择最大行数。

Suppose any employee is having 4 transaction rows and another is having only one row then how to select max rows for those employees. 假设任何雇员有4个交易行,而另一雇员只有一个交易行,那么如何为这些雇员选择最大行。

I am having job table I want to fetch max row number for employee to fetch the latest transaction for that employee I'd tried following 我有工作表,我想获取员工的最大行号,以获取我尝试关注的该员工的最新交易

With CTE as (
Select 
My fields,
Rownum = row_number() over(partition by emplid order by date) from jobtable
Where 
Myconditions
)
Select *  from CTE  B left outer join 
CTE A on A.emplid  = B.emplid 
Where 
A.rownum = (select max(a2.rownum) from jobtable a2)

Do left join is required above or it is not at all needed ? 上面是否需要左连接,还是根本不需要左连接? Please tell me how to fetch rownum if only 1 row exist for any employees as above query is fetching only employees which are having.greatest rownum in whole table 请告诉我如果任何员工仅存在1行,则如何获取rownum,因为上述查询仅获取整个表中具有最伟大rownum的员工

With CTE as (
    Select
       My fields,
       Rownum = row_number() over(partition by emplid order by date DESC)
    from jobtable
    Where 
       Myconditions
)

SELECT *
FROM
    cte
WHERE
    RowNum = 1

Just reverse the order of your ROW_NUMBER and and select where it equals 1. Row numbers can be ascending (ASC) or descending (DESC). 只需反转ROW_NUMBER的顺序并选择等于1的位置即可。行号可以升序(ASC)或降序(DESC)。 So if you want the most recent date to get the latest record ORDER BY date DESC , if you want the earliest record first you would choose ORDER BY date ASC (or date) 因此,如果您希望最近的日期获得最新的记录ORDER BY date DESC ,如果您想最早的记录最早,则可以选择ORDER BY date ASC (or date)

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

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