如何获取日期范围内的数据总和

时间:2019-07-16 07:11:44

标签: sql sql-server

我的英语说得不太好。抱歉

我想检索该时期的特定数据并汇总这些数据

示例数据集;

CREATE TABLE stackoverflow (
DT date,
Part_number varchAr(10),
sales_volume int
)
insert into stackoverflow values('2018-03-01','HDD','10000');
insert into stackoverflow values('2018-03-01','SDD','50000');
insert into stackoverflow values('2018-03-03','HDD','40000');
insert into stackoverflow values('2018-03-03','SDD','50000');
insert into stackoverflow values('2018-03-05','SDD','90000');
insert into stackoverflow values('2018-03-07','HDD','50000');
insert into stackoverflow values('2018-03-07','HDD','40000');
insert into stackoverflow values('2018-03-08','SDD','20000');
insert into stackoverflow values('2018-03-08','HDD','30000');
insert into stackoverflow values('2018-03-09','SDD','10000');
insert into stackoverflow values('2018-03-11','HDD','20000');

select * from stackoverflow;

这是我尝试过的查询。

select DT,Part_number,sales_volume,SUM(sales_volume) as sum_sv
from stackoverflow
where dt between '2018-03-01' and '2018-03-07'
GROUP BY DT,Part_number,sales_volume
having Part_number='SDD'
order by Part_number;

查询结果

2018-03-01  SDD 50000   50000
2018-03-03  SDD 50000   50000
2018-03-05  SDD 90000   90000

所需的输出

DT          Part_number       sum_s/v
2018-03-05     SDD            190000

1 个答案:

答案 0 :(得分:2)

尝试以下查询:

select max(DT) as DT, Part_number, sum(sales_volume) as sum_sv
  from stackoverflow
 where dt between '2018-03-01' and '2018-03-07'
   and Part_number = 'SDD'
 group by Part_number
 order by Part_number