1

我有一张表,其中包含员工的每日总计和开始日期,我需要回顾 3 个月以查看员工工作了多少天。

这是我的sql查询:

    SELECT
    EMPNO,
    CONVERT(VARCHAR(10), STARTDATE,101),
    ROW_NUMBER() OVER (ORDER BY PERSONNUM) AS 'ROWCOUNT'
    FROM EMPLOYEE
    WHERE STARTDATE BETWENN DATEADD(month, -3, GETDATE()) and GETDATE()
    GROUP BY EMPNO,STARTDATE
    ORDER BY EMPNO

结果

   EMPNO      STARTDATE               ROWCOUNT
   TEST108    09/13/2013              1
   TEST108    09/16/2013              2
   TEST108    09/17/2013              3
   TEST108    09/19/2013              4
   TEST109    09/04/2013              5
   TEST109    09/05/2013              6
   TEST109    09/06/2013              7
   TEST110    09/03/2013              9
   TEST110    09/04/2013             10
   TEST110    09/05/2013             11

期望的结果

   EMPNO           ROWCOUNT
   TEST108         4
   TEST109         3
   TEST110         3

谢谢,

4

4 回答 4

1

不能用计数吗?

SELECT EMPNO, COUNT(EMPNO) AS [ROWCOUNT]
FROM EMPLOYEE
WHERE STARTDATE BETWEEN DATEADD(month, -3, GETDATE()) and GETDATE()
GROUP BY EMPNO
ORDER BY EMPNO
于 2013-09-25T07:02:55.843 回答
1

试试这个——

SELECT  EMPNO
    ,   [ROWCOUNT] = COUNT(1)
FROM dbo.Employee
WHERE StartDate BETWEEN DATEADD(MONTH, -3, GETDATE()) AND GETDATE()
GROUP BY EMPNO
ORDER BY EMPNO --[ROWCOUNT] DESC
于 2013-09-25T07:04:04.617 回答
1

尝试这个

SELECT
EMPNO,COUNT(STARTDATE)
FROM EMPLOYEE
WHERE STARTDATE BETWEEN DATEADD(month, -3, GETDATE()) and GETDATE()
GROUP BY EMPNO
ORDER BY EMPNO
于 2013-09-25T07:04:18.130 回答
1

您可以将此 CTE 与ROW_NUMBER和一起使用COUNT(*)OVER

WITH CTE AS
(
    SELECT EMPNO, STARTDATE, 
           RN = ROW_NUMBER() OVER (PARTITION BY EMPNO ORDER BY STARTDATE DESC),
           [ROWCOUNT] = COUNT(*) OVER (PARTITION BY EMPNO)
    FROM dbo.EMPLOYEE
    WHERE STARTDATE BETWEEN DATEADD(month, -3, GETDATE()) and GETDATE()
)
SELECT EMPNO, STARTDATE, [ROWCOUNT]
FROM CTE
WHERE RN = 1

DEMO

为分区中的ROW_NUMBER每一行返回一个数字(类似于GROUP BY EMPNO),并允许选择所有列而无需聚合所有列。返回每个分区的COUNT(*)OVER总行数,这样就可以了。我使用ROW_NUMBERjust 来删除重复项。

于 2013-09-25T07:06:44.527 回答