SQL請教? |
尚未結案
|
writeman
初階會員 ![]() ![]() 發表:31 回覆:34 積分:28 註冊:2004-02-17 發送簡訊給我 |
最近都在寫SQL SERVER的STORED PROCEDURE 還是新手 問題特別多 :) 假如我的RECORD長成這樣 NO DATE QTY -- ---- --- 1 9301 100 1 9302 200 1 9303 300 1 9304 500 2 9301 200 2 9302 200 2 9303 300 2 9304 200 要SELECT成每個人一年內分成每兩個月的合計 像這樣 NO 1-2月 3-4月 5-6月 7-8月 9-10月 11-12月 -- ----- ----- ----- ----- ------ ------- 1 300 800 0 0 0 0 2 400 500 0 0 0 0 該如何做呢? |
StrongLemon
高階會員 ![]() ![]() ![]() ![]() 發表:10 回覆:166 積分:105 註冊:2004-04-18 發送簡訊給我 |
您好:參見以下範例,我寫的還沒有很完整,剩下的就給您自己補了。
//Create 一個 TmpTable Create Table #Report (No int, Month12 numeric(20,5), Month34 numeric(20,5), Month56 numeric(20,5), Month78 numeric(20,5), Month910 numeric(20,5), Month1112 numeric(20,5) ) //宣告變數 declare @NO int declare @QTY numeric(20,5) declare @YEAR int declare @Month int declare @STRDATESTART char(4) declare @STRDATEEND char(4) //選擇條件年月跟組合成@STRDATE->'YYMM' //自己寫吧 declare #c1 cursor FAST_FORWARD for select distinct No from RECORD open #c1 fetch next from #c1 into @NO while @@fetch_status = 0 begin //1,2月 insert into #Report (No,Month12,Month34,Month56,Month78,Month910,Month1112) values(@NO,0,0,0,0,0,0) set @STRDATESTART='9301' set @STRDATEEND='9302' Set @QTY=(select sum(QTY) from RECORD where NO=@NO and DATE between @STRDATESTART and @STRDATEEND update RECORD set Month12=@QTY where NO=@NO //3,4月..以下省略跟1,2月一樣作法 fetch next from #c1 into @NO end close #c1 deallocate #c1 select * from #Report |
BOSS
中階會員 ![]() ![]() ![]() 發表:70 回覆:79 積分:64 註冊:2006-11-01 發送簡訊給我 |
select no_,sum(dt01) '1-2月' ,sum(dt02) '3-4月',sum(dt03) '5-6月',sum(dt04) '7-8月',sum(dt05) '9-10月', sum(dt06) '11-12月' from ( select no_, case when (date_='9301') or date_='9302' then sum(qty_) else 0 end dt01, case when (date_='9303') or date_='9304' then sum(qty_) else 0 end dt02, case when (date_='9305') or date_='9306' then sum(qty_) else 0 end dt03, case when (date_='9307') or date_='9308' then sum(qty_) else 0 end dt04, case when (date_='9309') or date_='9310' then sum(qty_) else 0 end dt05, case when (date_='9311') or date_='9312' then sum(qty_) else 0 end dt06 from aa1 group by no_,date_)a group by no_ order by no_ |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |