我的表格employee
包含name
,startdate
,endate
列:
name | startdate | enddate
--------------------------------
A | 12/12/2012 | 12/12/2014
B | 05/08/2006 | 07/11/2009
我想要这样的结果:
name | Year of Employee
-------------------------
A | 2012
A | 2013
A | 2014
B | 2006
B | 2007
B | 2008
B | 2009
我必须在这里使用loop
和/或cross join
吗?
答案 0 :(得分:0)
创建样本表
CREATE TABLE #test(name VARCHAR(10), startdate DATE, enddate DATE)
插入一些样本数据
INSERT INTO #test VALUES ('A', '12/12/2012', '12/12/2014')
,('B', '05/08/2006', '07/11/2009')
使用递归CTE
;WITH CTE AS (
SELECT name, DATEPART(YEAR, startdate) AS yr FROM #test
UNION ALL
SELECT #test.name, yr + 1
FROM CTE
INNER JOIN #test ON #test.name = CTE.name
WHERE yr < DATEPART(YEAR, enddate)
)
SELECT name, yr AS [Year of Employee]
FROM CTE
ORDER BY name, yr
输出
name Year of Employee
A 2012
A 2013
A 2014
B 2006
B 2007
B 2008
B 2009
答案 1 :(得分:0)
定义并填充提供此内容的CalYear
表:
CalYearStartDate CalYearEndDate
2005-01-01 2005-12-12
2006-01-01 2006-12-12
2007-01-01 2007-12-12
2008-01-01 2008-12-12
2009-01-01 2009-12-12
2010-01-01 2010-12-12
2011-01-01 2011-12-12
2012-01-01 2012-12-12
2013-01-01 2013-12-12
2014-01-01 2014-12-12
定义并填充提供此内容的Emp
表:
EmpName StartDate EndDate
A 2012-12-12 2014-12-12
B 2006-05-08 2009-07-11
使用此查询来检索结果:
Select EmpName,
CalYearStartDate
From Emp
Inner
Join CalYear
on YEAR(CalYearStartDate) >= YEAR(Emp.StartDate)
and YEAR(CalYearEndDate) <= YEAR(Emp.EndDate)
答案 2 :(得分:0)
创建声明:
CREATE TABLE #test(name VARCHAR(10), startdate DATE, enddate DATE)
INSERT INTO #test VALUES ('A', '12/12/2012', '12/12/2014')
,('B', '05/08/2006', '07/11/2009')
查询:
SELECT t.name, YEAR(DATEADD(year,n.number, t.startdate)) AS Year
FROM #test t,
(SELECT number
FROM master..spt_values
WHERE [type] = 'P') n
WHERE startdate <= DATEADD(year,n.number, t.startdate)
AND enddate >= DATEADD(year,n.number, t.startdate)
结果:
name Year
A 2012
A 2013
A 2014
B 2006
B 2007
B 2008
B 2009