如何查找每个值的日期之间的总和

发布于 2024-12-29 14:05:25 字数 529 浏览 0 评论 0原文

表 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,因为起始日期和截止日期大于当前日期。

如何查询此计算..?

任何建议....

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....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何止钟意 2025-01-05 14:05:25
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

添加到日期差异的加一是为了考虑部分天数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文