将Distinct和TOP 1结合在Union | SQL 服务器 2012

Combining Distinct and TOP 1 in Union | SQL SERVER 2012

我有以下 SQL 查询:

SELECT DISTINCT LEFT (employeeidno, 4)deptcode 
from employeemasterfile 
ORDER BY deptcode ASC

产生 DISTINCTD001D051

SELECT TOP 1 RIGHT (employeeidno, 7) empno 
from employeemasterfile  
ORDER BY empno DESC 

产生 0000267

的值

我在这里想要实现的是 D001D051 的每个 DISTINCT 值都应该产生它的 TOP 1 值。

这就是我想要达到的目标。

deptcode :D001; empno: 0000016

deptcode :D002; empno: 0000024

deptcode :D004; empno: 0000029

deptcode :D005; empno: 0000020

deptcode :D006; empno: 0000056

deptcode :D007; empno: 0000164

deptcode will display all the unique D001-D007, and empno will display the TOP1 for every unique deptcode.

select deptcode, empno 
from
(
SELECT TOP 1 RIGHT (employeeidno, 7) empno from employeemasterfile  ORDER BY empno DESC
UNION
SELECT DISTINCT LEFT (employeeidno, 4)deptcode from employeemasterfile ORDER BY deptcode ASC
) results
ORDER BY deptcode

不幸的是我不能这样做,因为如果我要添加一个新参数,UNION 将不起作用。

我可以就此问题寻求您的帮助吗?

示例数据如下所示

D0010000001
D0010000002
D0010000003
D0010000004
D0010000005
D0010000006
D0010000007
D0010000008
D0010000009
D0010000010
D0010000011
D0010000012
D0010000013
D0010000014
D0010000015
D0010000016
D0020000001
D0020000002
D0020000003
D0020000004
D0020000005
D0020000006
D0020000007
D0020000008
D0020000009
D0020000010
D0020000011
D0020000012
D0020000013
D0020000014
D0020000015
D0020000016
D0020000017
D0020000018
D0020000019

依此类推,直到 D0520000001

你可以使用 row_number()

select deptcode,empno from
 ( select LEFT (employeeidno, 4) deptcode,
          RIGHT (employeeidno, 7) empno,
  row_number()over(partition by LEFT (employeeidno, 4) ordere by RIGHT (employeeidno, 7) desc)
 from employeemasterfile
) a where a.rn=1

你可以用 GROUP BY LEFT(employeeidno, 4):

SELECT 
  LEFT(employeeidno, 4) deptcode,
  MAX(RIGHT(employeeidno, 7)) empno
FROM employeemasterfile
GROUP BY LEFT(employeeidno, 4)
ORDER BY LEFT(employeeidno, 4)

据我了解聚合应该做到这一点。

SELECT left(employeeidno, 4) deptcode,
       max(right(employeeidno, 7)) empno
       FROM employeemasterfile
       GROUP BY left(employeeidno, 4)
       ORDER BY left(employeeidno, 4);

编辑:

我会试着解释一下:

您可以想象 GROUP BY left(employeeidno, 4) 将记录集划分为子集。在每个子集中,left(employeeidno, 4),即 deptno 相同,并且没有两个子集具有相同的 deptno。现在在每个子集中 max(right(employeeidno, 7)) 取最大值 right(employeeidno, 7) 即最大值 empno。 (使用 TOP 1 将结果限制在一行中的 ORDER BY empno DESC 也会让你得到最大值。)然后通过获取每个子集的 deptno 来生成最终结果(即每个子集deptno 一次)和最大值 empno.