SELECT USERINFO.UserID
,SUM(DATEDIFF(DAY, DateFrom, DateTo) + 1) AS total_leave_days
FROM USERINFO
INNER JOIN CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID
LEFT OUTER JOIN DEPARTMENTS ON DEPARTMENTS.DEPTID = USERINFO.DEFAULTDEPTID
left join AuthLeave on AuthLeave.userid = userinfo.userid
and AuthLeave.DATEFROM>='2014-01-01'
and AuthLeave.DATETO<='2014-06-30'
WHERE (CHECKINOUT.CHECKTIME >= '2014-01-01')
AND (CHECKINOUT.CHECKTIME <= '2014-06-30')
AND DEPARTMENTS.DEPTNAME = 'GEN/SUP-TBL'
GROUP BY USERINFO.UserID
这是我的代码,我可以在下面输出
UserID total_leave_days
35 NULL
350 NULL
30 NULL
10 735
167 NULL
21 920
1 621
224 NULL
因此我的Authleave表格数据不正确:
UserID DATEFROM DATETO
1 2014-03-10 2014-03-15
10 2014-05-28 2014-05-29
21 2014-05-27 2014-05-27
1 2014-04-10 2014-04-15
从现在起我想要输出如下:
UserID total_leave_days
35 NULL
350 NULL
30 NULL
10 2
167 NULL
21 1
1 12
224 NULL
所以我该怎么做?
答案 0 :(得分:-1)
你能试试这个SQL
吗?SELECT U.[UserID],
C.[Leave]
FROM [USERINFO] U
LEFT JOIN (SELECT [UserID],
SUM(DATEDIFF(DAY,[DATEFROM],[DATETO])) [Leave]
FROM [CHECKINOUT]
WHERE [CHECKTIME] >= '2014-01-01' AND [CHECKTIME] <= '2014-06-30'
GROUP BY [UserID]
) C ON U.[USERID] = C.[USERID]
LEFT JOIN [DEPARTMENTS] D ON D.[DEPTID] = U.[DEFAULTDEPTID]
LEFT JOIN [AuthLeave] A on A.[userid] = U.[userid]
WHERE D.[DEPTNAME] = 'GEN/SUP-TBL'
enter code here
编辑:
请参阅下面的SQL,我对Table Names感到有点困惑。
SELECT U.[UserID],
L.[Leave]
FROM [USERINFO] U
JOIN CHECKINOUT C ON U.USERID = C.USERID
LEFT JOIN [DEPARTMENTS] D ON D.[DEPTID] = U.[DEFAULTDEPTID]
LEFT JOIN (SELECT [UserID],
SUM(DATEDIFF(DAY,[DATEFROM],[DATETO])) [Leave]
FROM [AuthLeave]
WHERE [DATEFROM] >= '2014-01-01' AND [DATETO] <= '2014-06-30'
GROUP BY [UserID]
) L ON L.[UserID] =U.[UserID]
WHERE D.[DEPTNAME] = 'GEN/SUP-TBL'
AND C.[CHECKTIME] >= '2014-01-01' AND C.[CHECKTIME] <= '2014-06-30'