有下面兩張表
這種情況下查詢出來的結果按下面的形式顯示:
ID | Name | Tm | Score |
001 | 小小 | 2011-1-1 | 90 |
001 | 小小 | 2011-2-1 | 80 |
002 | 小強 | 2011-1-5 | 75 |
這種結果是通過Tab_Score inner jion Tab_Students 來實現的,導致每個時間有一個考核分數,然后進行羅列顯示。
然而有時客戶希望得到下面的顯示結果。
ID | Name | 年份 | 月份 | 上旬分數 | 中旬分數 | 下旬分數 | 全月分數 |
也就是每個月份有一個顯示記錄
作為一個和用戶交互的、可分頁存儲過程一般包括下面幾個輸入參數:
開始時間、結束時間、開始取值位置,結束取值位置、搜索條件、排序條件
下面是通過臨時表來重構數據的一個查詢:
--參數 declare @startdate datetime='2011-01-15 08:00:00.000' declare @enddate datetime='2012-10-22 08:00:00.000' declare @startIndex int=1 declare @endIndex int=100 declare @conditionStr nvarchar(200)='1<>0' declare @orderStr nvarchar(200)='ID desc' --臨時表 drop table #MyTable create table #MyTable ( ID nvarchar(50) not null, Name nvarchar(50) not null, Yr int not null, Mth int not null, UpScore int not null, MiddleScore int not null, DownScore int not null, AllScore int not null, ) --獲取月初時間 set @startdate=DATEADD(MM,DATEDIFF(MM,0,@startdate),0) set @enddate=DATEADD(MM,DATEDIFF(MM,0,@enddate), 0) --向臨時表添加數據 while @startdate<@enddate begin insert into #MyTable (ID,Name,Yr,Mth,UpScore,MiddleScore,DownScore,AllScore) select Tab_Students.ID, Tab_Students.Name, DATEPART(YEAR,@startdate) as Yr, DATEPART(MONTH,@startdate) as Mth, ( select isnull(sum(Score),0) from Tab_Score where Tab_Score.ID = Tab_Students.ID and TM between @startdate and DATEADD(DAY,10,@startdate) )as UpScore, ( select isnull(sum(Score),0) from Tab_Score where Tab_Score.ID = Tab_Students.ID and TM between DATEADD(DAY,10,@startdate) and DATEADD(DAY,20,@startdate) )as MiddleScore, ( select isnull(sum(Score),0) from Tab_Score where Tab_Score.ID = Tab_Students.ID and TM between DATEADD(DAY,20,@startdate) and DATEADD(mm,1,@startdate) )as DownScore, ( select isnull(sum(Score),0) from Tab_Score where Tab_Score.ID = Tab_Students.ID and TM between @startdate and DATEADD(mm,1,@startdate) )as AllScore from Tab_Students set @startdate=DATEADD(mm,1,@startdate) end --結果查詢 declare @selectStr nvarchar(1000) set @selectStr='select * from #MyTable where ' + @conditionStr +' order by '+@orderStr exec (@selectStr)
--結果表 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[#MyTable]') AND type in (N'U')) DROP TABLE [dbo].[#MyTable] create table #MyTable ( DRP decimal(8,2), TM datetime ) declare @DRP decimal(8,2) --查詢時段:8:00 .....8:00 雨量統計算結束時間的8:00-8:00 while @startTime<@endTime begin select @DRP= isnull(sum(DRP),0) FROM ST_PPTN_R where STCD = @STCD and TM >DATEADD(hh,-1,@startTime) and TM<=@startTime and --向前推一個小時到當前時間 STCD+','+cast(TM as Nvarchar) not in (select ST_PPTN_R_Add.STCD+','+cast(ST_PPTN_R_Add.TM as Nvarchar) from ST_PPTN_R_Add) insert into #MyTable(DRP,TM) values ( @DRP, @startTime--降雨結束時間 ) set @startTime=DATEADD(hh,1,@startTime) end select * from #MyTable