SELECT DISTINCT (DATEDIFF(DAY, '2014-06-01', '2014-06-30') + 1) - DATEDIFF(WEEK, '2014-06-01', '2014-06-30') * 2 - (CASE WHEN DATEPART(WEEKDAY, '2014-06-01') = 5 THEN 1 ELSE 0 END) - (CASE WHEN DATEPART(WEEKDAY, '2014-06-30') = 6 THEN 1 ELSE 0 END) AS TotalWorkingDays, COUNT(DISTINCT DATEADD(d, 0,DATEDIFF(d, 0, CHECKINOUT.CHECKTIME))) AS workingdays,
USERINFO.NAME,
case when '08:00:00.000' > cast(convert(char(8),min(checktime),8) as datetime) THEN NULL
ELSE
cast(dateadd(minute,datediff(minute,'08:00:00.000',min(checktime)),'00:00')AS dateTIME) END as LATEIN ,
case when '17:00:00.000' < cast(convert(char(8),max(checktime),8) as datetime) THEN NULL
ELSE
cast(dateadd(minute,datediff(minute,max(checktime),'17:00:00.000'),'00:00')AS dateTIME)END as LATEOUT
FROM USERINFO left JOIN CHECKINOUT ON CHECKINOUT.USERID = USERINFO.USERID
left join departments on deptid = userinfo.DEFAULTDEPTID
WHERE(DEPARTMENTS.DEPTNAME = 'GEN/SUP-TBL') AND (CHECKINOUT.CHECKTIME >='2014-06-01') AND (CHECKINOUT.CHECKTIME <='2014-06-30') and name='Gokul Gopalakrishnan'
GROUP BY USERINFO.NAME,checktime
这是我的查询,它给出了以下输出:
TotalWorkingDays workingdays NAMER LATEIN LATEOUT
22 1 abc NULL 1785-07-17 09:24:00.000
22 1 abc NULL 1785-07-18 00:15:00.000
22 1 abc NULL 1785-07-31 00:30:00.000
22 1 abc 2014-06-01 00:39:00.000 1785-08-02 01:00:00.000
22 1 abc 2014-06-01 09:14:00.000 NULL
但现在我想要输出如下:
TotalWorkingDays workingdays NAME TOTAL LATEIN TOTAL LATEOUT
22 5 abc 09:53:00.000 10:69:00.000
那我该如何在sql server中执行此操作?
答案 0 :(得分:1)
您需要做的是将第一个选择的结果插入到声明的表中, 然后对声明的表的列求和。 在我的代码中存在1785年的问题(这就是我使用2000代替的原因),但我正在努力:)
DECLARE @unSummedResults TABLE (totalWorkingDays int, workingdays int, name nvarchar(10), latein smalldatetime, lateout smalldatetime)
insert into @unSummedResults (totalWorkingDays, workingdays, name, latein, lateout) values (22, 1, 'abc', NULL, '2000-07-17 09:24:00.000')
insert into @unSummedResults (totalWorkingDays, workingdays, name, latein, lateout) values (22, 1, 'abc', NULL, '2000-07-18 00:15:00.000')
insert into @unSummedResults (totalWorkingDays, workingdays, name, latein, lateout) values (22, 1, 'abc', NULL, ' 2000-07-31 00:30:00.000')
insert into @unSummedResults (totalWorkingDays, workingdays, name, latein, lateout) values (22, 1, 'abc', '2014-06-01 00:39:00.000', '2000-08-02 01:00:00.000')
insert into @unSummedResults (totalWorkingDays, workingdays, name, latein, lateout) values (22, 1, 'abc', '2014-06-01 09:14:00.000', NULL)
select distinct unSummedResults.totalWorkingDays, sum(workingdays), name,
convert(varchar(5), sum(datepart(hh, latein))) + ':' +
convert(varchar(5), sum(datepart(n, latein))) + ':' +
convert(varchar(5), sum(datepart(s, latein))),
convert(varchar(5), sum(datepart(hh, lateout))) + ':' +
convert(varchar(5), sum(datepart(n, lateout))) + ':' +
convert(varchar(5), sum(datepart(s, lateout)))
from @unSummedResults as unSummedResults
group by totalWorkingDays, name
好运!