2

我的 sql 表中有以下数据:

 Tran_Date          |  Amount 
2013-05-01 20:09:49 | 50.00
2013-05-02 04:09:49 | 50.00
2013-05-02 20:09:49 | 500.00

我想在第二天早上 5 点之前计算金额。结果应如下所示。

Amount 
100.00 
500.00

我尝试了以下代码,但结果是错误的:

SELECT DATEADD(hh, 5, DATEADD(dd, DATEDIFF(dd, 0, DATEADD(dd,1,f.TRAN_DATE)) AS sDate, 
       SUM(Amount) 
FROM TRAN_TABLE 
GROUP BY sDate

如何实现这一目标?谢谢

4

2 回答 2

4

对于任何 SQL Server 版本

select [Date]=DATEADD(DAY,DATEDIFF(DAY,0,DATEADD(HOUR,-5,Tran_Date)),0),
       Total=SUM(Amount)
from tbl
group by DATEADD(DAY,DATEDIFF(DAY,0,DATEADD(HOUR,-5,Tran_Date)),0)
order by [Date];

对于 SQL Server 2008+,您可以使用 DATE 数据类型

select [Date]=CAST(DATEADD(HOUR,-5,Tran_Date) as date),
       Total=SUM(Amount)
from tbl
group by CAST(DATEADD(HOUR,-5,Tran_Date) as date)
order by [Date];
于 2013-05-18T08:47:25.400 回答
1

您需要在减去 5 小时后提取 DATE 并按此分组:

SELECT
    CAST(DATEADD(hour, -5, TRAN_DATE) AS DATE) AS sDate,
    SUM(Amount)
FROM TRAN_TABLE
GROUP BY CAST(DATEADD(hour, -5, TRAN_DATE) AS DATE)
于 2013-05-18T10:53:55.377 回答