说我有这张桌子:
EMPLOYEES
----------------------------------------------------------
first last ID hire terminated wage
------ --------- --- ---------- ----------- ----
Ruth Halburg 1 2010-05-15 2017-03-01 2000
Sally Hallson 2 2010-08-20 NULL 5000
Merry Hallway 3 2011-01-24 NULL 3000
我需要获取仍在公司工作的员工的最长“雇用”日期和最短“雇用”日期之间的天数差(终止= NULL)。
我知道我需要使用
Select *, datediff(d, max(hire), min(hire) as Difference
From Employees
Where terminated = NULL
但是我不确定如何使它工作。
答案 0 :(得分:0)
假设您正在使用mysql datediff返回天数差异
以及查询
如果终止符是字符串,则必须检查'NULL' 如果是日期,则应检查为空
Select datediff(max(hire), min(hire)) as Difference
From Employees
Where terminated = 'NULL'
或
Select datediff( max(hire), min(hire)) as Difference
From Employees
Where terminated is null
如果要使用聚合功能,则不能在group by中未提及的select子句中使用列:
select last, datediff(max(hire), min(hire)) as Difference
From Employees
Where terminated is null
group by last
或
select last, datediff(max(hire), min(hire)) as Difference
From Employees
group by last
对于sql-server,而不是datediff(date1,date2),请添加时间间隔参数
SELECT DATEDIFF(d, max(hire),min(hire))
答案 1 :(得分:0)
我相信你想要
Select id,
datediff(day, min(hire) max(hire)) as Difference
From Employees
group by id
having count(terminated) < count(*) -- at least one NULL value
请注意,datediff()
的语法使用该函数的SQL Server版本。我认为这对您的问题并不重要。关键部分是group by
和having
子句。