27,580
社区成员
发帖
与我相关
我的任务
分享select sum(销售金额)as total from 表名:1 where left(时间,7)='2011\08' group by 区县 order by SUM(销售金额) DESC
select 区县, sum(销售金额) from 表1 where convert(varchar(7),时间,120)='2011-08' group by 区县 order by SUM(销售金额) DESC
select 区县, convert(varchar(7),时间,23) 时间, sum(销售金额) 销售金额 from table1 group by 区县,convert(varchar(7),时间,23)
use Tempdb
go
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([区县] nvarchar(50),[时间] DATETIME,[销售金额] int)
Insert #T
select N'渝北',N'2011-08-20',200 union all
select N'渝北',N'2011-09-25',400 union all
--select N'巴南',N'2011-08-25',400 union all --去掉一條記錄
select N'巴南',N'2011-09-24',400 union all
select N'渝中',N'2011-08-24',400 union all
select N'渝中',N'2011-09-24',400
Go
select
区县,
时间=ISNULL(MIN(convert(varchar(7),时间,120)),'2011-08'),
销售金额=isnull(sum(销售金额) ,0)
from #T
WHERE convert(varchar(7),时间,120)='2011-08'
group by all 区县
/*
区县 时间 销售金额
-------------------------------------------------- ------- -----------
巴南 2011-08 0
渝中 2011-08 400
渝北 2011-08 200
*/
use Tempdb
go
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([区县] nvarchar(50),[时间] DATETIME,[销售金额] int)
Insert #T
select N'渝北',N'2011-08-20',200 union all
select N'渝北',N'2011-09-25',400 union all
select N'巴南',N'2011-08-25',400 union all
select N'巴南',N'2011-09-24',400 union all
select N'渝中',N'2011-08-24',400 union all
select N'渝中',N'2011-09-24',400
Go
DECLARE @s NVARCHAR(4000)
SELECT @s=ISNULL(@s+',',' select ')+QUOTENAME([区县])+N'=sum(case when [区县]=N'''+[区县]+N''' then [销售金额] else 0 end)' FROM #T GROUP BY [区县]
EXEC(@s+'
from #T
WHERE convert(varchar(7),时间,120)=''2011-08''
'
)
/*
巴南 渝中 渝北
----------- ----------- -----------
400 400 200
*/
use Tempdb
go
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([区县] nvarchar(50),[时间] DATETIME,[销售金额] int)
Insert #T
select N'渝北',N'2011-08-20',200 union all
select N'渝北',N'2011-09-25',400 union all
select N'巴南',N'2011-08-25',400 union all
select N'巴南',N'2011-09-24',400 union all
select N'渝中',N'2011-08-24',400 union all
select N'渝中',N'2011-09-24',400
Go
DECLARE @s NVARCHAR(4000)
SELECT @s=ISNULL(@s+',',' select ')+QUOTENAME([区县])+N'=sum(case when [区县]=N'''+[区县]+N''' then [销售金额] else 0 end)' FROM #T GROUP BY [区县]
EXEC(@s+'
from #T
WHERE convert(varchar(7),时间,120)=''2011-08''
group by 区县,convert(varchar(7),时间,120)'
)
/*
巴南 渝中 渝北
----------- ----------- -----------
400 0 0
0 400 0
0 0 200
*/
select
区县,sum(销售金额) from 表1
where
datediff(mm, 时间,'2011-08-01')=0
group by
区县select 区县,sum(销售金额) from 表1
where convert(char(7),时间,120) ='2011-08'
group by 区县
order by sum(销售金额) descselect 区县,sum(销售金额) from 表1
where convert(char(7),时间,120) ='2011-08'
group by 区县select 区县, 时间=convert(varchar(7),时间,120), 销售金额=sum(销售金额) from table1 group by 区县,convert(varchar(7),时间,120)select 区县, 时间=convert(varchar(7),时间,120), 销售金额=sum(销售金额) frp, table1 group by 区县,convert(varchar(7),时间,120)