- select
- bizMonth,
- sum(retailCount) retailCount
- from
- SHOP_RETAIL
- where
- bizData >= DateAdd(m,-9,getdate())
- and bizData <= getdate()
- group by bizMonth
- order by bizMonth
这个是我初始的SQL语句 查询结果类似下面的
月份 数量
3 100
4 200
6 240
11 400
那我现在想要近10个月的数量情况
就像下面这样的效果
月份 数量
4 200
5 0
6 240
7 0
8 0
9 0
10 0
11 400
12 0
1 0
最后的语句如下:
- select top 100 id=identity(int,1,1) into #tmp from syscolumns a,syscolumns b
- select
- datepart(m,dateadd(m,-id+1,getdate())) as mon,
- (case when qty is null then 0 else qty end) as qty
- from #tmp left join
- (select bizMonth, sum(retailCount) as qty
- from shop_retail
- group by bizMonth ) mm on datepart(m,dateadd(m,-id+1,getdate()))=bizMonth
- where datediff(m,dateadd(m,-id,getdate()),getdate())<=10
- drop table #tmp