我创建了一个SQL查询,该查询返回一个人一个月在一个月中的总天数,现在我想添加总数列和3种叶子列,即[休闲假],[带薪假],[免费休假]。
简而言之,我想在[休假],[带薪休假]和[免费休假]中添加总计列。
我的查询如下:
;WITH ToPivot
AS ( SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN
(
(datepart(hour, chk_in)) is null
OR (datepart(hour, chk_out)) is null
)
then
0
WHEN
(
(datepart(hour, chk_in)) >= 12
OR (datepart(hour, chk_out)) < 16
AND ((datepart(hour, chk_out)) - (datepart(hour, chk_in))) < 6
)
THEN
0.5
ELSE
1
END) AS late, TypeOfLeaves.leave_type, Userleavetyp.no_of_days
FROM Users
INNER JOIN time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE (Users.FK_Status = 1)
),
LateTotals AS (
SELECT T.username, Total = SUM(late),T.leave_type,T.no_of_days
FROM ToPivot AS T
WHERE T.date BETWEEN '2018-07-01' AND '2018-07-31' GROUP BY T.username,T.leave_type,T.no_of_days
)
SELECT distinct(pv2.username) as original ,PV2.*,L.Total
FROM ToPivot AS P
PIVOT (SUM(late) FOR date IN ("2018-07-01", "2018-07-02", "2018-07-03", "2018-07-04", "2018-07-05", "2018-07-06", "2018-07-07", "2018-07-08", "2018-07-09", "2018-07-10", "2018-07-11", "2018-07-12", "2018-07-13", "2018-07-14", "2018-07-15", "2018-07-16", "2018-07-17", "2018-07-18", "2018-07-19", "2018-07-20", "2018-07-21", "2018-07-22", "2018-07-23", "2018-07-24", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-28", "2018-07-29", "2018-07-30", "2018-07-31")) AS pv1
PIVOT (SUM(no_of_days) FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])) AS pv2
LEFT JOIN LateTotals AS L ON L.username = pv2.username
此代码的输出如下:
答案 0 :(得分:0)
我相信您只需要按以下方式更改选择语句。 从这个:
SELECT distinct(pv2.username) as original ,PV2.*,L.Total
对此:
SELECT distinct(pv2.username) as original ,PV2.*,L.Total,
CASE WHEN PV2.[Casual Leave] IS NULL THEN 0 ELSE PV2.[Casual Leave] +
CASE WHEN PV2.[Paid Leave] IS NULL THEN 0 ELSE PV2.[Paid Leave] +
CASE WHEN PV2.[Complimentary Leave] IS NULL THEN 0 ELSE PV2.[Complimentary Leave]
AS [Total Leave]