我试图选择拥有最早SDate的员工的姓名。我尝试了以下方法:
SELECT [name]
FROM [employee]
where [dept] in ('Finance', 'HR', 'IT')
and [SDate] = min([SDate]);
我被抛出了一个错误。这并不奇怪,因为我在where子句中有一个聚合函数。所以,我修改了它:
SELECT [name]
FROM [employee]
where [dept] in ('Finance', 'HR', 'IT')
group by [name]
having [SDate] = min([SDate]);
但它仍然无法奏效。我应该如何构建我的T-SQL,以便获得具有最小SDate的员工的姓名?
答案 0 :(得分:2)
使用order by
和top
:
SELECT top 1 [name]
FROM [employee]
WHERE [dept] in ('Finance', 'HR', 'IT')
ORDER BY sdate desc;
答案 1 :(得分:2)
DECLARE @minDate Date
SELECT
@mindate=MIN(sDate)
FROM
employee E
WHERE
[dept] IN ('Finance', 'HR', 'IT');
SELECT
[name]
FROM
[employee]
WHERE
[dept] IN ('Finance', 'HR', 'IT')
and [sDate] = @minDate;