表1
Period datefrom dateto code id
01/2012 18/12/2011 28/12/2011 A Emp1
01/2012 11/01/2012 14/01/2012 B Emp1
02/2012 20/12/2011 25/12/2011 A Emp2
02/2012 01/02/2012 08/01/2012 B Emp2 'from and to date is greater than current date.
.....
我希望将datefrom和dateto之间的总值与系统日期验证相结合
预期产出
ID PERIOD A B TOTAL
Emp1 01/2012 11 4 15
Emp2 02/2012 6 0 6
'B为0,因为起始日期大于当前日期。
如何查询此计算..?
任何建议......
答案 0 :(得分:1)
SET DATEFORMAT dmy
SELECT
ID,
Period,
(SELECT ISNULL(SUM(DATEDIFF(DAY,datefrom,dateto) + 1),0)
FROM Test
WHERE DATEDIFF(DAY,datefrom,dateto) > 0 and code = 'A'
and x.Period = Period and x.id = id)
as ACode,
(SELECT ISNULL(SUM(DATEDIFF(DAY,datefrom,dateto) + 1),0)
FROM Test
WHERE DATEDIFF(DAY,datefrom,dateto) > 0 and code = 'B'
and x.Period = Period and x.id = id)
as Bcode
FROM TABLENAME x
GROUP BY
Period,
ID
添加到日期差异的加号是占用部分日。