sql動態列查詢

2022-07-10 03:36:09 字數 2016 閱讀 5512

最近開發是遇到sql查詢時,以查詢結果作為列名,也就是動態列查詢,案列如下:

declare @sql varchar(max);

set @sql='select fname 銷售經理,fnumber as 客戶代號 ,

sum(case when 月份 = ''01'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '01') + '],

sum(case when 月份 = ''02'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '02') +'],

sum(case when 月份 = ''03'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '03') +'],

sum(case when 月份 = ''04'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '04') +'],

sum(case when 月份 = ''05'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '05') +'],

sum(case when 月份 = ''06'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '06') +'],

sum(case when 月份 = ''07'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '07') +'],

sum(case when 月份 = ''08'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '08') +'],

sum(case when 月份 = ''09'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '09') +'],

sum(case when 月份 = ''10'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '10') +'],

sum(case when 月份 = ''11'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '11') +'],

sum(case when 月份 = ''12'' then (bordlocal) else 0 end ) as [' + (select top 1 年月 from #orderamount where 月份 = '12') +'],

(case when sum(bordlocal)<0 then 0 else sum(bordlocal) end ) as 接單金額, (case when sum(bordlocal)<0 then 0 else sum(bordlocal) end )* 0.001 as 獎金 from #orderamount t

group by fname,fnumber

order by fname,right(fnumber,2)'

exec(@sql);

執行結果如下:

sql動態查詢

所以我有乙個從網頁傳遞的dict。我想基於dict動態構建查詢。我知道我可以做 session.query myclass filter by web dict 但是,僅當值完全匹配時才起作用。我需要做 像 過濾。我最好的嘗試使用 dict 屬性 for k,v in web dict.items ...

SQL裡動態生成列

一般這種比較複雜一點都用乙個儲存過程來寫比較好。因為單一的檢視不能滿足我們的需求。類似這種,有規律可循的列。如果按照原始的方法 case when then end。我估計是又繁瑣又累,純粹的體力活啊。其實我最開始的時候就是醬寫的 不過好在有大神師傅的指點,簡單多了,而且這個區間值是可以改變的。如下...

mysql動態sql無效 sql動態列的問題?

一種效率並不高的方案,我想想看有沒有更加高效的方法,想到後在來編輯 create table ttd pname varchar 30 pcode int,cname varchar 30 ccode int,yname varchar 30 ycode int insert into ttd pn...