SQL查询中的SQL查询总和

时间:2016-10-24 20:32:03

标签: sql sql-server tsql

我有两个表,Employees和EmployeeVacations。我正在尝试进行SQL查询,以获得每个员工休假时间和当前余额的总和。这是我当前的SQL查询:

SELECT
    e.PIN,
    e.FirstName,
    e.LastName,
    e.Uniform,
    e.AL_Cap,
    ev.Value AS '10/1 Balance',
    (SELECT
        SUM(value)
    FROM EmployeeVacations
    WHERE CreationDate >= '2016-10-01'
    AND Vacation_Type = 'Taken'
    AND Vacation_Kind = 'AL'
    AND EmployeeId = 13)
    AS Taken
FROM    employees e,
        EmployeeVacations ev
WHERE e.Id = ev.EmployeeId
AND ev.IsHistory = 0
AND ev.Vacation_Type = 'Forward'
AND ev.Vacation_Kind = 'AL'
AND EmployeeId = 13
ORDER BY e.LastName, e.FirstName

如果我选择一名员工,这是有效的。如果我删除“where EmployeeId = 13”,我会得到所有员工的清单,其中每个人的总休假总和(如1300小时)。我如何分解它,因此它只显示每个员工的特定拍摄?

2 个答案:

答案 0 :(得分:2)

您需要一个核心查询,其中子查询使用来自" parent"的值。查询。

SELECT e.PIN ...
    (select SUM(value) .... WHERE EmployeeID = e.id) as taken
                                               ^^^^^

请注意,这些效率非常低,因为内部查询必须为父查询的每一行执行一次。在很多情况下,您可能最好通过适当的分组重写为传统的JOIN查询。

答案 1 :(得分:1)

只是猜测你也可能想要总和而不是单个转发记录......这是一个按EmployeeVacations聚合EmployeeId的查询:

select
  e.pin,
  e.firstname,
  e.lastname,
  e.uniform,
  e.al_cap,
  ev.forward_sum as "10/1 balance",
  ev.taken_sum as taken
from employee e
left join
(
  select     
    employeeid,
    sum(case when vacation_type = 'Forward' 
             and ishistory = 0 then value else 0 end) as forward_sum,
    sum(case when vacation_type = 'Taken' 
             and creationdate >= '20161001' then value else 0 end) as taken_sum,
  from employeevacations
  where vacation_kind = 'AL'
  group by employeeid
) ev on ev.employeeid = e.employeeid
order by e.lastname, e.firstname;

请......

  • 使用显式连接而不是1992年之前的逗号分隔连接,以提高可读性并减少错误。
  • 对别名使用双引号;单引号用于字符串文字。
  • 使用' yyyymmdd'日期;它是SQL Server中支持的日期文字格式。