-->在线等待,统计销售数量的SQL语句!!!
问题:
1、现在有一个表SaleList,字段如下:
ProID-------dDate-------nNum
产品ID 日期 销售数量
001 2013-05-01 10
001 2013-05-03 11
001 2013-07-05 15
002 2013-06-06 20
002 2013-07-01 10
003 2013-08-06 10
003 2013-08-09 20
003 2013-08-10 30
003 2013-08-11 40
查询条件:(YYYY-MM)~(YYYY-MM),就是查询某年某月到某年某月每个产品在其时间段内的每中产品每个月的销售总和。
001 2013-05 21
001 2013-07 15
002 2013-06 20
002 2013-07 10
003 2013-08 100
[解决办法]
if object_id('Tempdb..#t') is not null drop table #t
create table #t(
id int identity(1,1) not null,
ProID nvarchar(100) null,
dDate datetime null,
nNum int null
)
Insert Into #t
select '001','2013-05-01',10 union all
select '001','2013-05-03',11 union all
select '001','2013-07-05',15 union all
select '002','2013-06-06',20 union all
select '002','2013-07-01',10 union all
select '003','2013-08-06',10 union all
select '003','2013-08-09',20 union all
select '003','2013-08-10',30 union all
select '003','2013-08-11',40
declare @begin datetime
declare @end datetime
set @begin='2013-05-01 0:0:0'
set @end='2013-08-31 23:59:59'
;with cte as(
select ProID,convert(nvarchar(7),dDate,120) as dDate,nNum from #t
where dDate between @begin and @end
)
select ProID,dDate,sum(nNum)as nSum from cte group by ProID,dDate
order by ProID
--------------------
(9 行受影响)
ProID dDate nSum
---------------------------------------------------------------------------------------------------- ------- -----------
001 2013-05 21
001 2013-07 15
002 2013-06 20
002 2013-07 10
003 2013-08 100
(5 行受影响)