SQL总和值从日期时间字段开始逐日

时间:2018-12-21 09:31:59

标签: sql sql-server tsql sql-server-2016

我有一张桌子:

Date                    NETTO   VAT
2018-09-18 13:06:48.287 15.00   2.80
2018-07-21 17:32:28.620 8.55    1.60
2018-09-07 12:43:07.487 50.70   9.48
2018-09-07 19:32:06.530 57.20   10.70
2018-09-03 17:12:13.837 79.00   14.77
2018-09-08 14:54:25.367 110.45  20.65
2018-10-01 13:04:53.917 60.90   11.39

日期为datetime类型 像2018-06-15 12:22:43.312

我尝试将datetime转换为date,但无法查看NETTO和增值税的总和

select 
  CONVERT(date, data_sp, 111) As Date, 
  SUM(w_csb) as NETTO , 
  SUM(w_vat) as VAT 
from 
  sales
Group by 
  data_sp
Order by 
  data_sp

我想得到这样的结果: 日复一日

2018-06-15  3335.75 236.68
2018-06-16  199.00  37.21
2018-06-17  1115.00 232.80

2 个答案:

答案 0 :(得分:2)

您可以在下面使用cast(data_sp as date)进行日期转换,也可以将其添加到group by子句中

select cast(data_sp as date) As Date, SUM(w_csb) as NETTO , SUM(w_vat) as VAT 
from sales 
Group by cast(data_sp as date) 
order by cast(data_sp as date)

答案 1 :(得分:1)

fa06's answer应该适合您,或者,如果将datetime转换为varchar而不是date,您会得到稍微更整洁的输出(没有零维时间):

SELECT 
  CONVERT(varchar(10), data_sp, 111) AS Date, 
  SUM(w_csb) AS NETTO, 
  SUM(w_vat) AS VAT 
FROM
  sales
GROUP BY 
  CONVERT(varchar(10), data_sp, 111) 
ORDER BY 
  CONVERT(varchar(10), data_sp, 111) 

重要的一点是,缩短的日期必须在GROUP BYORDER BY子句以及SELECT子句中,否则只能按原始日期,该日期仍包含时间,因此日期仍被视为唯一值-因此不可分组。

根据上面的示例数据,我的查询将输出:

Date        NETTO   VAT
2018/07/21  8.55    1.60
2018/09/03  79.00   14.77
2018/09/07  107.90  20.18
2018/09/08  110.45  20.65
2018/09/18  15.00   2.80
2018/10/01  60.90   11.39

您的大多数日期无论如何都只会出现一次,但是您可以看到它正确地分组了2018-09-07

工作示例(包括我和fa06的查询):https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=ed0d4ca3ebd8e45e02be41aaf86c2ef4