如何在SQL Server中按日期对列中的值求和

时间:2018-08-28 14:38:18

标签: sql-server sql-server-2008

我有以下内容:

Name |Dur |DateTime  
Bill |10  |8/12/2018 07:00:00  
Sue  |4   |8/10/2018 09:00:00  
Joe  |23  |8/13/2018 07:15:00  
Bill |13  |8/13/2018 09:15:00  
Sue  |4   |8/10/2018 19:00:00  
Sue  |23  |8/13/2018 07:25:00  
Bill |10  |8/12/2018 15:18:00  
Sue  |4   |8/11/2018 13:00:00  
Joe  |23  |8/14/2018 07:15:00

我想结束:

Name |Tot|Date  
Bill |20 |8/12/2018  
Bill |13 |8/13/2018  
Sue  | 8 |8/10/2018  
Sue  | 4 |8/11/2018  
Joe  |23 |8/13/2018  
Joe  |23 |8/14/2018  

所以基本上,每天对每个名字的Dur进行求和。

我尝试过:

SELECT  
    Name,  
    SUM([Dur]) AS Tot,  
    (CONVERT(VARCHAR, [DateTime], 101)) AS sDateTime  
FROM 
    DailyTransactions   
GROUP BY 
    DATEADD(day, DATEDIFF(day, 0, DateTime), 0), Name 

2 个答案:

答案 0 :(得分:0)

您接近...只是按照您在列转换中使用的相同逻辑进行分组。

SELECT  
    Name,  
    SUM([Dur]) AS Tot,  
    (CONVERT(VARCHAR, [DateTime], 101))AS sDateTime  
FROM 
    DailyTransactions   
GROUP BY 
    (CONVERT(VARCHAR, [DateTime], 101))

答案 1 :(得分:0)

这应该可以完成您的工作

   SELECT  
        Name,  
        SUM([Dur]) AS Tot,  
        cast(DateTime as Date) AS Date  
    FROM 
        DailyTransactions   
    GROUP BY 
        cast(DateTime as Date), Name