SQLServer 使用變數動態行轉列

2021-07-10 21:24:38 字數 1815 閱讀 5285

drop table #test

create table #test

(id int identity(1,1) primary key,

bizdate varchar(50),

type varchar(50),

qty float

)insert into #test

select '20110501','a',20.5 union all

select '20110501','b',98 union all

select '20110501','c',100.5 union all

select '20110501','a',32 union all

select '20110501','c',76.8 union all

select '20110502','b',58 union all

select '20110502','a',111 union all

select '20110502','a',51 union all

select '20110502','a',85 union all

select '20110502','b',52 union all

select '20110502','c',43 union all

select '20110503','a',158 union all

select '20110503','c',58 union all

select '20110503','b',28 union all

select '20110503','b',65 union all

select '20110503','a',11 union all

select '20110503','a',25 union all

select '20110503','c',63

declare @sql varchar(8000)

set @sql = 'select type' 

select @sql = @sql + ' , sum(case when bizdate=''' + bizdate + ''' then qty else 0 end) [' + bizdate + ']'

from (select distinct bizdate from #test) as a order by bizdate--此行的sql用於找出不重複的日期,也就是結果集中所有的日期

set @sql = @sql + ' from #test a group by type'

print @sql

exec(@sql)

--列印出來的完整sql是:

/*ps. sqlserver裡的中括號作用:

若表名、欄位名、列名等與資料庫裡的關鍵字有衝突,則可以給該錶名或欄位名加上""以識區別。

上面的例子中是以日期作為列名,也可用""標識

*/

SQLServer 使用變數動態行轉列

drop table test create table test id int identity 1,1 primary key,bizdate varchar 50 type varchar 50 qty float insert into test select 20110501 a 20.5...

SQLServer系統變數使用

1 identity 返回最後插入的標識值。這個變數很有用,當你插入一行資料時,想同時獲得該行的的id 標示列 就可以用 identity 示例 下面的示例向帶有標識列的表中插入一行,並用 identity 顯示在新行中使用的標識值。insert into jobs job desc,min lvl...

SQL Server動態SQL與變數繫結

有時候動態sql需要進行變數的賦值,這個時候就需要呼叫系統的儲存過程sp executesql了。使用中還是有些注意事項,如下 字元型字段需宣告為nvarchar型別 declare strsql nvarchar 1000 value str nvarchar 254 動態sql拼接 set st...