SQL Server在同一查询中的不同日期执行相同的计算

时间:2017-06-02 18:23:54

标签: sql sql-server date

我有两个独立的(基本)查询基本相同,除了一个是计算一个月到日之和,另一个是计算年初至今的总和。我希望每位员工在他们的名字旁边都有一个月份和年初至今的列,而不是有两个单独的表。我已经尝试了工会和一些子查询,但我仍然遇到麻烦。我查看了很多资源,但还没找到我能用的东西。

--Query 1:
SELECT 
    A.EMPLOYEENUMBER AS 'Employee No.', 
    B.ENTITYNAME AS 'Employee Office', 
    B.NAME1 AS 'Employee Information', 
    SUM(A.NUMBEROF) AS 'Ent. Qty'
FROM prod.DAILYTIMESHEETLINE A
JOIN prod.EMPLOYEE B on A.EMPLOYEENUMBER = B.EMPLOYEENUMBER
WHERE A.THEDATE BETWEEN '2017.04.01' AND '2017.04.30'
GROUP BY A.EMPLOYEENUMBER, B.NAME1, B.ENTITYNAME
ORDER BY A.EMPLOYEENUMBER


--Query 2:
SELECT 
    A.EMPLOYEENUMBER AS 'Employee No.', 
    B.ENTITYNAME AS 'Employee Office', 
    B.NAME1 AS 'Employee Information', 
    SUM(A.NUMBEROF) AS 'Ent. Qty'
FROM prod.DAILYTIMESHEETLINE A
JOIN prod.EMPLOYEE B on A.EMPLOYEENUMBER = B.EMPLOYEENUMBER
WHERE A.THEDATE BETWEEN '2017.01.01' AND '2017.04.30'
GROUP BY A.EMPLOYEENUMBER, B.NAME1, B.ENTITYNAME
ORDER BY A.EMPLOYEENUMBER

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    A.EMPLOYEENUMBER AS 'Employee No.', 
    B.ENTITYNAME AS 'Employee Office', 
    B.NAME1 AS 'Employee Information',
    SUM(case when A.THEDATE BETWEEN '2017.01.01' AND '2017.04.30' then A.NUMBEROF else null end) AS 'Ent. Qty1', 
    SUM(case when A.THEDATE BETWEEN '2017.04.01' AND '2017.04.30' then A.NUMBEROF else null end) AS 'Ent. Qty2'
FROM prod.DAILYTIMESHEETLINE A
JOIN prod.EMPLOYEE B on A.EMPLOYEENUMBER = B.EMPLOYEENUMBER
WHERE A.THEDATE BETWEEN '2017.01.01' AND '2017.04.30'
GROUP BY A.EMPLOYEENUMBER, B.NAME1, B.ENTITYNAME
ORDER BY A.EMPLOYEENUMBER

小心到哪里:我让BETWEEN' 2017.01.01' AND' 2017.04.30'因为' 2017.01.01' < ' 2017年4月1日' ,修改结果;)