按年

时间:2018-01-16 06:54:15

标签: sql-server sql-server-2012 group-by

考虑以下数据集。

表名:TBL_EMPLOYEE

EMP_NUMBER      EMP_JOIN_DATE

001             2014-02-08
002             2014-03-15
003             2014-05-20
004             2015-05-24
005             2015-10-24
006             2017-01-30
007             2017-12-06

我需要得到的。过去十年加入的员工如下

必填结果

year    (no of joined employees count)

2018            0
2017            2
2016            0
2015            2
2014            3 

我试过bellow sql。

SELECT top 10 DATEPART(yyyy, EMP_JOIN_DATE) AS RESIGN_YEAR,COUNT(EMP_NUMBER)AS COUNTT
FROM TBL_EMPLOYEE
WHERE DATEPART(yyyy, EMP_JOIN_DATE) <= 2018 
GROUP BY DATEPART(yyyy, EMP_JOIN_DATE)
ORDER BY EMP_JOIN_DATE DESC

但它返回以下结果

year    (no of joined employees count)

2017            2
2015            2
2014            3

4 个答案:

答案 0 :(得分:3)

@Scrat,你可以使用参考文件中给出的数字表或SQL numbers table function

然后您可以将此表用作FROM子句中的主表,如下所示

select * from dbo.NumbersTable(2008,2018,1)

enter image description here

然后你可以简单地LEFT JOIN你的表和开发,并加入这两个多年

;with cte as (
SELECT top 10 DATEPART(yyyy, EMP_JOIN_DATE) AS RESIGN_YEAR,COUNT(EMP_NUMBER)AS COUNTT
FROM TBL_EMPLOYEE
WHERE DATEPART(yyyy, EMP_JOIN_DATE) <= 2018 
GROUP BY DATEPART(yyyy, EMP_JOIN_DATE)
)
select * 
from dbo.NumbersTable(2008,2018,1) nt
left join cte on nt.i = cte.RESIGN_YEAR
ORDER BY EMP_JOIN_DATE DESC

答案 1 :(得分:1)

尝试以下查询:

WITH yearlist AS 
(
    SELECT (DATEPART(Year,getdate())-10) as year
    UNION all
    SELECT yl.year + 1 as year
    FROM yearlist yl
    WHERE yl.year + 1 <= YEAR(GetDate())
)

SELECT Y.year ,ISNULL(A.[No of Employees],0) [No of Employees]
FROM yearlist Y
LEFT JOIN
 ( 
SELECT YEAR(EMP_JOIN_DATE) [Year],Count(YEAR(EMP_JOIN_DATE)) [No of Employees]
FROM TBL_EMPLOYEE
WHERE DATEDIFF(YEAR,EMP_JOIN_DATE,GETDATE()) < 10
GROUP BY YEAR(EMP_JOIN_DATE)
 ) A ON A.Year = Y.year
ORDER BY Y.year DESC;

希望它有效!!

答案 2 :(得分:1)

我是以另一种方式完成的。试试这个

SELECT @min_year = min(EMP_JOIN_DATE)
    ,@max_year = max(EMP_JOIN_DATE)
FROM @TBL_EMPLOYEE;

WITH CTE
AS (
    SELECT datepart(year, @min_year) AS yr

    UNION ALL

    SELECT yr + 1
    FROM CTE
    WHERE yr <= datepart(year, @max_year)
    )
SELECT TOP 10 yr AS RESIGN_YEAR
    ,COUNT(EMP_NUMBER) AS COUNTT
FROM CTE
LEFT JOIN @TBL_EMPLOYEE ON year(EMP_JOIN_DATE) = yr
WHERE yr <= 2018
GROUP BY yr
ORDER BY yr ASC

答案 3 :(得分:0)

试试这个

DECLARE @Strt INT=2007,@End INT = 2017
;WITH YR
AS
(
    SELECT
       MyYear = @Strt

    UNION ALL

    SELECT
       MyYear = MyYear+1
       FROM YR
          WHERE MyYear < @End

)
SELECT
    YR.MyYear,
    JoinCnt = COUNT(EMP.EMP_NUMBER)
    FROM YR
       LEFT JOIN Tbl_EmploYee EMP
          ON YEAR(EMP.EMP_JOIN_DATE) = YR.MyYear
       GROUP BY YR.MyYear