所以这个问题可能已经得到了解答,但搜索甚至提问都有点困难。
我想查询一个表并以多种方式过滤它。在下面的例子中,我想弄清楚每个部门的第一个员工是谁。
Table A
employee_id | dept_id | start_date | name | age | sex
1 | 1 | 1/5/2000 | Bill | 25 | m
2 | 2 | 2/5/2000 | Biff | 30 | m
3 | 2 | 3/6/2002 | Gil | 31 | m
4 | 2 | 3/7/2002 | Mar | 27 | f
5 | 3 | 1/5/2000 | Tina | 24 | f
6 | 3 | 1/5/2000 | Lin | 21 | f
所以,如果我做SELECT dept_id, min(start_date) from Table A GROUP BY dept_id ORDER BY min(start_date)
我会得到
dept_id | start_date
1 | 1/5/2000
2 | 2/5/2000
3 | 1/5/2000
哪个是正确的信息,除了我需要其他列。我不能只将它们添加到SELECT语句中,因为它们不在GROUP BY中,我不能将它们添加到GROUP BY中,因为这样我就无法获得正确的结果。
此评论有点回答了我的问题,但未完全SQL Select Distinct Values, but order by a different value 因为我尝试在连接中做一个子查询并在SELECT中添加字段,但它仍然希望字段在GROUP BY中。
请告知
编辑: 我想得到的结果是
employee_id | dept_id | start_date | name | age | sex
1 | 1 | 1/5/2000 | Bill | 25 | m
2 | 2 | 2/5/2000 | Biff | 30 | m
5 | 3 | 1/5/2000 | Tina | 24 | f
答案 0 :(得分:2)
您想使用row_number()
:
select employee_id, dept_id, start_date, name, age, sex
from (select a.*, row_number() over (partition by dept_id order by start_date) as seqnum
from table a
) a
where seqnum = 1;
row_number()
是一个为行组分配序号的函数。这些组由partition by
子句定义,因此在这种情况下,同一部门中的每个人都在同一个组中。根据{{1}}子句按顺序分配数字。因此,最早的开始日期的值为1. order by
子句然后选择这些记录。
答案 1 :(得分:2)
找出每个部门的第一人
DECLARE @Table TABLE(employee_id INT,dept_id INT,[start_date] DATE
,name VARCHAR(10),age INT, sex CHAR(1))
INSERT INTO @Table VALUES
(1,1,'1/5/2000','Bill',25,'m'),
(2,2,'2/5/2000','Biff',30,'m'),
(3,2,'3/6/2002','Gil',31,'m'),
(4,2,'3/7/2002','Mar',27,'f'),
(5,3,'1/5/2000','Tina',24,'f'),
(6,3,'1/5/2000','Lin',21,'f')
SELECT * FROM
(
SELECT *
, rn = ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY [start_date] ASC)
FROM @Table
)Q
WHERE rn = 1
结果集
╔═════════════╦═════════╦════════════╦══════╦═════╦═════╦════╗
║ employee_id ║ dept_id ║ start_date ║ name ║ age ║ sex ║ rn ║
╠═════════════╬═════════╬════════════╬══════╬═════╬═════╬════╣
║ 1 ║ 1 ║ 2000-01-05 ║ Bill ║ 25 ║ m ║ 1 ║
║ 2 ║ 2 ║ 2000-02-05 ║ Biff ║ 30 ║ m ║ 1 ║
║ 5 ║ 3 ║ 2000-01-05 ║ Tina ║ 24 ║ f ║ 1 ║
╚═════════════╩═════════╩════════════╩══════╩═════╩═════╩════╝