SQL Server 表字段值轉列名 示例

2022-08-26 23:24:28 字數 915 閱讀 3797

前幾天,同事問我怎樣把字段值轉換成欄位列,就寫了乙個最簡單的demo分享一下。

**如下:

-- 建立測試表以及新增測試資料

create table #temp(a money,b varchar(10))

/*insert into #temp(a,b) values(10,'1點')

insert into #temp(a,b) values(20,'2點')

insert into #temp(a,b) values(20,'3點')

insert into #temp(a,b) values(20,'4點')

insert into #temp(a,b) values(20,'5點')

insert into #temp(a,b) values(30,'6點')

insert into #temp(a,b) values(20,'7點')

insert into #temp(a,b) values(48,'8點')

insert into #temp(a,b) values(20,'9點')

insert into #temp(a,b) values(15,'10點')

*/select * from #temp

-- 查詢結果

declare @sql nvarchar(max)='';

select @sql=@sql+ (case @sql when '' then '' else ',' end)+'max(case b when '''+b+''' then a else 0 end) ['+b+']' from #temp;

set @sql='select '+@sql+' from #temp;';

exec sp_executesql @sql;

--drop table #temp

表字段的處理 Sql Server

目錄 表的建立 建立約束 檢視約束 刪除約束 插入資料 增加字段 刪除字段 create table student 學號 char 8 not null,姓名 char 8 not null,性別 char 2 not null,出生日期 date default getdate 班級 char ...

SQL Server 表字段值轉換成欄位名稱 二

上次寫了個比較簡單的只有兩個欄位的例子,經要求在寫個 3 個字段的示例 貼上來與大家共勉一下 如果你們有更好的方法,提供一下,感激不盡。示例如下 drop table temp testcol valuetoname 建立測試表 前提 每天每個會員只有一條記錄 create table temp t...

對Sql Server表字段進行修改

通用式 alter table 表名 add 欄位名 字段屬性 default 預設值 default 是可選引數 增加字段 alter table 表名 add 欄位名 smallint default 0 增加數字字段,整型,預設值為0 alter table 表名 add 欄位名 int de...