我需要一个SQL(SQL Server),根据当前的sg获取最早的日期。下面是当前sg为4-3的示例表(当前,因为结束日期是1900-01-01)。我想得到每位员工实际开始的日期(2015-01-01)。我真的需要一些帮助。
empno position sg date_from date_to
4508 ADMIN AIDE IV 4-3 2017-01-01 1900-01-01
4508 ADMIN AIDE IV 4-3 2016-01-01 2016-12-31
4508 ADMIN AIDE IV 4-3 2015-01-01 2015-12-31
4508 ADMIN AIDE IV 4-2 2014-01-01 2014-12-31
4508 ADMIN AIDE IV 4-2 2013-01-01 2013-12-31
1207 AIRCRAFT MECHANIC I 6-1 1988-01-01 1989-06-30
1207 AIRCRAFT MECHANIC II 8-7 2006-05-08 2015-12-31
1207 AIRCRAFT MECHANIC II 8-8 2016-01-01 1900-01-01
0889 DATA ENTRY OPERATOR 1-1 2000-12-12 2001-06-30
0889 ADMIN ASSISTANT VI 12-5 2017-03-10 1900-01-01
0889 ADMIN ASSISTANT VI 12-5 2016-01-01 2016-12-31
答案 0 :(得分:1)
如果我理解正确,你可以用内部查询
来做到这一点select min(date_from)
from yourTable
where sg = (
select sg
from yourTable
where date_to = '1900-01-01'
)
或加入
select min(t1.date_from)
from yourTable t1
join yourTable t2
on t1.sg = t2.sg
where t2.date_to = '1900-01-01'
修改强>
要获得每个职位的最短日期,最简单的方法是将第二个查询调整为:
select t1.position, min(t1.date_from)
from yourTable t1
join yourTable t2
on t1.sg = t2.sg and
t1.position = t2.position
where t2.date_to = '1900-01-01'
group by t1.position
修改2
由于要求是获取empno
列中每个值的最小日期,您需要做的是
select t1.empno, min(t1.date_from)
from yourTable t1
join yourTable t2
on t1.sg = t2.sg and
t1.empno = t2.empno
where t2.date_to = '1900-01-01'
group by t1.empno
您可以在工作中看到它here
答案 1 :(得分:1)
如果sg不能有多个位置,您可以使用下一个查询
SELECT t.position, t.sg, MIN(date_from) AS date_from
FROM @t AS t
INNER JOIN
(select sg from @t where date_to = '19000101') as cur
ON t.sg = cur.sg
GROUP BY t.position, t.sg
答案 2 :(得分:1)
解决方案:
SELECT TOP 1 *
FROM YourTableNameHere
ORDER BY Sg DESC, Date_From
更多详情:
将ORDER BY与TOP 1结合使用。下面我使用了一个可以在NEW QUERY窗口中运行的临时表。
试试这个:
CREATE TABLE #TempTable(
Position varchar(20),
Sg varchar(3),
Date_From datetime,
Date_To datetime)
INSERT INTO #TempTable (Position, Sg, Date_From, Date_To)
SELECT
'ADMIN AIDE IV', '4-3', '2017-01-01', '1900-01-01'
UNION
SELECT
'ADMIN AIDE IV', '4-3', '2016-01-01', '2016-12-31'
UNION
SELECT
'ADMIN AIDE IV', '4-3', '2015-01-01', '2015-12-31'
UNION
SELECT
'ADMIN AIDE IV', '4-2', '2014-01-01', '2014-12-31'
UNION
SELECT
'ADMIN AIDE IV', '4-2', '2013-01-01', '2013-12-31'
SELECT TOP 1 *
FROM #TempTable
ORDER BY Sg DESC, Date_From
答案 3 :(得分:0)
请使用以下查询:
DECLARE @t TABLE
(ID INT IDENTITY (1,1),position VARCHAR(20), sg VARCHAR(10),date_from DATE,date_to DATE)
INSERT INTO @t
VALUES
('ADMIN AIDE IV','4-3','2017-01-01','1900-01-01'),
('ADMIN AIDE IV','4-3','2016-01-01','2016-12-31'),
('ADMIN AIDE IV','4-3','2015-01-01','2015-12-31'),
('ADMIN AIDE IV','4-2','2014-01-01','2014-12-31'),
('ADMIN AIDE IV','4-2','2013-01-01','2013-12-31')
SELECT
MIN(t1.date_from) AS [Earliest Date]
FROM
@t t1 INNER JOIN @t t2 ON t1.sg = t2.sg
WHERE
t2.date_to ='1900-01-01'