一個很是常見的報表,分析會員組成比例 以及最新增加狀況 和上月同期會員增加狀況。
比較特殊一點的是 報表中的 普通會員 和 金卡會員 臨時會員 銀卡會員 等列 都是根據會員等級配置表動態生成的(即我是不知道會有多少個vip等級的)。
sql以下(有點挫的感受 應該會有更優雅的方式實現):
select N=1, AgentID, AgentBigArea, AgentName,CusALevel,CusCreateDate into #temp from Customer inner join CusAccount on
CusAVIPNo = VIPNo inner join Agent on AgentID = CusAgentID where CusStatus = 1 and CusCreateDate<'2016-03-31 23:59:59'
--插入區域小計
insert into #temp select SUM(N),-1,AgentBigArea+'_小計',AgentBigArea+'_小計',CusALevel,'' from #temp group by AgentBigArea,CusALevel
--插入總計
insert into #temp select SUM(N),-1,'總合計','總合計',CusALevel,'' from #temp where AgentBigArea not like '%小計%' group by CusALevel
declare @sql nvarchar(max)
-- 空格這麼可能是由於不能設置字符串長度 很挫 暫時這樣處理吧
set @sql = 'select '' '' as ''增加率'', Agentname as ''分銷商'',agentid,AgentBigArea as ''區域'', SUM(case when CusCreateDate>''2016-03-01'' and CusCreateDate<''2016-03-31'' then N else 0 end) as ''本期'' ,
SUM(case when CusCreateDate>Dateadd(MONTH, -1, ''2016/3/1 0:00:00'') and CusCreateDate<Dateadd(MONTH, -1, ''2016/3/31 0:00:00'') then N else 0 end) as ''上期'',
SUM(N) as ''總會員數'''
--動態行轉列
SELECT @sql = @sql + ',SUM(case CusALevel when ' +CAST(CusLevelID as nvarchar(10))+' then N else 0 end) as [' +CusLevelName+']'
FROM
(SELECT TOP 10000 CusLevelID,CusLevelName
FROM CusLevel
) AS a
print @sql
SET @sql = @sql + ' into ##temp1 from #temp group by agentname,agentid,AgentBigArea order by AgentBigArea '
EXEC (@sql)
--我的以爲比較挫的地方 用到了全局臨時表 select * into #temp2 from ##temp1 drop table ##temp1 --計算區域小計行的本期和上期 update #temp2 set 本期=bq,上期=sq from #temp2 inner join (select 區域+'_小計' as AgentBigArea, SUM(上期) as sq,SUM(本期) as bq from #temp2 where 區域 not like '%小計%' group by 區域 ) as t on t.AgentBigArea = #temp2.區域 where #temp2.區域 like '%小計%' --計算總合計的本期和上期 update #temp2 set 本期=(select SUM(本期) from #temp2 where 區域 like '%小計%' ),上期=(select SUM(上期) from #temp2 where 區域 like '%小計%' ) where 區域 = '總合計' --計算增加率 update #temp2 set 增加率 = (case 上期 when 0 then '' else convert(varchar(30),cast((本期-上期)/convert(decimal(10,2),上期) *100 as decimal(18,2)) )+'%' end) from #temp2 select * from #temp2