问题
Table1
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.
.....
i want to take total of value between datefrom and dateto with system date validation
Expected Output
ID PERIOD A B TOTAL
Emp1 01/2012 11 4 15
Emp2 02/2012 6 0 6
'B is 0 because from and to date is greater than current date.
How to make a query for this calcuatlion..?
Any suggestions....
回答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
The plus one added to the date diff is to account for part days.
来源:https://stackoverflow.com/questions/9043159/how-to-find-the-total-between-the-dates-for-each-values