我没有足够的积分来发布图片,但这里是我的桌面截图的链接:My query screen shot
我有一个SQL Server表,生病和员工休假时间。我们的代码未输入2016-08-01的远期余额(已修复)。我需要从2016-07-01(19.32)获取远期余额并添加2016-06-30(6.66)的收益并减去2016-07-01至2016-07-31之间的所有收益(3,6)和1.5)并将其插入类似于第3行和第10行的新记录中,但远期余额应为13.48。
如何为所有EmployeeID
编写SQL语句来执行此操作?我试图使用SUM但是没有成功。
Select Value
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Forward'
and CreationDate = '2016-07-01'
and EmployeeId = 1775
加:
Select Value
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Earned'
and CreationDate = '2016-06-30'
and EmployeeId = 1775
减:
Select SUM(Value) as TotalTaken
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Taken'
and CreationDate >= '2016-07-01'
and CreationDate <= '2016-07-31'
and EmployeeId = 1775
然后从这三个值中取出值并插入新记录,如
INSERT into EmployeeVacations ([EmployeeId], [Vacation_Kind], [Vacation_Type], [CreationDate], [Value])
VALUES (1775, 'SL', 'Forward', '2016-08-01', 13.48)
答案 0 :(得分:2)
我没有重现您的数据,所以我无法对此进行测试,但我认为您应该采用这样的方法:
INSERT INTO EmployeeVacations ([EmployeeId], [Vacation_Kind], [Vacation_Type], [CreationDate], [Value])
SELECT EmployeeId, 'SL', 'Forward', '2016-08-01', SUM(Value)
FROM (
Select EmployeeId, Value
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Forward'
and CreationDate = '2016-07-01'
UNION ALL
Select EmployeeId, Value
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Earned'
and CreationDate = '2016-06-30'
UNION ALL
Select EmployeeId, -Value
From EmployeeVacations
Where Vacation_Kind = 'SL'
and Vacation_Type = 'Taken'
and CreationDate >= '2016-07-01'
and CreationDate <= '2016-07-31'
) SubQ
GROUP BY EmployeeId
正如您所看到的,我只是使用一个子查询,其中包含您需要的所有信息,而不是其他内容,然后我只是按员工对其进行分组。
当然,您应首先在没有INSERT
行的情况下运行它,以确保获得所需内容。
答案 1 :(得分:2)
尝试此查询:它应该为您提供所需的结果。首先检查一个员工,例如你的例子中的1775。然后测试另一名员工。然后在不指定任何员工ID的情况下运行(当前查询不指定任何员工ID。该部分已注释掉)。它可能需要很少的修改,但鉴于你的情况我怀疑。如果结果很好,那么你可以在插入语句中使用它,如@Andrew answer。
所示SELECT
EVF.EmployeeId
,'SL'
,'Forward'
,'2016-08-01'
,EVF.Value + EVE.EarnedLeave - EVT.TotalTaken AS Forward
FROM EmployeeVacations EVF
INNER JOIN
(
SELECT
EmployeeId
,Value AS EarnedLeave
FROM EmployeeVacations
WHERE
Vacation_Kind = 'SL'
AND Vacation_Type = 'Earned'
AND CreationDate = '2016-06-30'
) EVE ON EVE.EmployeeID = EVF.EmployeeId
INNER JOIN
(
SELECT
EmployeeId
,SUM(Value) AS TotalTaken
FROM EmployeeVacations
WHERE
Vacation_Kind = 'SL'
AND Vacation_Type = 'Taken'
AND CreationDate >= '2016-07-01'
AND CreationDate <= '2016-07-31'
GROUP BY EmployeeId
) EVT ON EVT.EmployeeId = EVF.EmployeeId
WHERE
Vacation_Kind = 'SL'
AND Vacation_Type = 'Forward'
AND CreationDate = '2016-07-01'
--AND EmployeeId = 1775