根據用戶在網站活動的記錄,生成一個按機型分組的月份報表的存儲過程.
這個存儲過程通過左聯接各個臨時表,然後生成一個與要在網頁上顯示的報表格式的目標視圖.
這樣可以直接在asp.net中用gridview綁定這個存儲過程,而不用寫一個.cs文件的代碼,便可以完成按機型分組的月份報表的任務.
存儲過程代碼如下:
CREATE PROC prc_MonthReporter_v_ClientAction
@iYear int,
@iMonth int
as
begin
begin transaction
select identity(int,1,1) id
,vSupportPType
,nGameName
,count(id) iVisitTimeCount
,count(DISTINCT nMID) iVisitUserCount
into #MonthVisitCount
from v_ClientAction
where iActionTypeId=1
and year(dActionTime)=@iYear and month(dActionTime)=@iMonth
group by vSupportPType,nGameName
order by vSupportPType
select identity(int,1,1) id
,vSupportPType
,nGameName
,count(DISTINCT nMID) iOrderUserCount
,cast(count(id)*2 as int) iIncomeing
into #MonthOrderCount
from v_ClientAction
where iActionTypeId=2
and year(dActionTime)=@iYear and month(dActionTime)=@iMonth
group by vSupportPType,nGameName
order by vSupportPType
select identity(int,1,1) id
,vSupportPType
,nGameName
,count(id) iDownloadTimeCount
,count(DISTINCT nMID) iDownloadUserCount
into #MonthDownloadCount
from v_ClientAction
where iActionTypeId=3
and year(dActionTime)=@iYear and month(dActionTime)=@iMonth
group by vSupportPType,nGameName
order by vSupportPType
select
#MonthVisitCount.vSupportPType [終端型號]
,#MonthVisitCount.nGameName [遊戲名稱]
,isnull(#MonthVisitCount.iVisitTimeCount,0) [訪問量]
,isnull(#MonthVisitCount.iVisitUserCount,0) [訪問用戶數]
,isnull(#MonthOrderCount.iOrderUserCount,0) [訂購人數]
,isnull(#MonthDownloadCount.iDownloadTimeCount,0) [成功下載次數]
,isnull(#MonthDownloadCount.iDownloadUserCount,0) [成功下載人數]
,isnull(#MonthOrderCount.iIncomeing,0) [收入(元)]
into #MonthReporter
from #MonthVisitCount
left outer join dbo.#MonthOrderCount
on #MonthVisitCount.vSupportPType=#MonthOrderCount.vSupportPType
and #MonthVisitCount.nGameName=#MonthOrderCount.nGameName
left outer join dbo.#MonthDownloadCount
on #MonthVisitCount.vSupportPType=#MonthDownloadCount.vSupportPType
and #MonthVisitCount.nGameName=#MonthDownloadCount.nGameName
order by #MonthVisitCount.id
--select * from #MonthVisitCount
--select * from #MonthOrderCount
--select * from #MonthDownloadCount
select * from #MonthReporter
if object_id('tempdb.dbo.#MonthVisitCount') is not null
drop table #MonthVisitCount
if object_id('tempdb.dbo.#MonthOrderCount') is not null
drop table #MonthOrderCount
if object_id('tempdb.dbo.#MonthDownloadCount')is not null
drop table #MonthDownloadCount
if object_id('tempdb.dbo.#MonthReporter')is not null
drop table #MonthReporter
commit transaction
end
GO
體會:
很多對數據庫操作的編程,只要數據庫中各表的關係設計得合理,都是可以能通過T-SQL來完成複雜的查詢,插入與更新,聯合等操作,然後達到接近業務需求邏輯的結果,再用編程與腳本語言來完成一些難以用T-SQL來完成的業務邏輯,是一個能讓應用更高效的思路方法.