How to find the total between the dates for each values

丶灬走出姿态 提交于 2019-12-24 12:43:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!