SQL小技巧 行列互轉,換行,根據條件顯示不同內容

2021-06-26 13:46:29 字數 2612 閱讀 8176

sql小技巧

1、行列互轉

(1)

--建立乙個表

create table tb1

( 姓名 varchar(10) ,

語文 int ,

數學 int ,

物理 int

)

--插入兩條資料

insert into tb1(姓名 , 語文 , 數學 , 物理) values('張三',74,83,93)

insert into tb1(姓名 , 語文 , 數學 , 物理) values('李四',74,84,94)

--行轉成列

select * from tb1

select * from

( select 姓名 as name , subject = '語文' , result = 語文 from tb1

union all

select 姓名 as name , subject = '數學' , result = 數學 from tb1

union all

select 姓名 as name , subject = '物理' , result = 物理 from tb1

) torder by name , case subject when '語文' then 1 when '數學' then 2 when '物理' then 3 when '總分' then 4 end

上面sql執行完成的結果如下圖:

2、換行

使用char(10)+char(13)即可換行並空行

使用char(10)、char(13)其中乙個即可換行

3、根據條件顯示不同內容

使用case when 條件 then 結果 else end 、case 字段 when  欄位的值 then 結果 end 兩種格式可以實現根據條件顯示不同內容。

例如:(1)

case when sta.cstatecode = sta_off.cstatecode then 

case when sta.cstatename = '正常' then cast(attd.fworkdays as nvarchar(100))

else sta.cstatename

endelse cast(attd.fworkdays as nvarchar(100))+'天'

end

解釋:上面一段的意思就是

if(sta.cstatecode == sta_off.cstatecode)else

} else

return的值就是最終這一列要顯示的值

(2)

sum(case c.cdefine2 when  0 then b.fworkdays end) as changbai
解釋:

double changbai;

for(int i=0;i最終得到的changbai變數就是要顯示的值 

4、兩行並一行

select ddocdate,cdefine1,bodya

=(stuff((select ','+cclassname+':'+cast(fworkdays as nvarchar(100))

--case when count(cdefine1)>1 then ','+cclassname end

from #attyeartemptable where ddocdate=att.ddocdate and cdefine1=att.cdefine1 and cpsn_num=att.cpsn_num for xml path('')),1,1,'')

(1)stuff方法:select stuff('abcdef', 2, 3, 'ijklmn')——意思是:

從第乙個字串 abcdef 的第 2 個位置 (b) 開始刪除三個字元,然後在刪除位置插入第二個字串,從而建立並返回乙個字串。              

stuff ( character_expression , start , length , replacewith_expression )

(2)select

*from

@hobby

forxml path(

'myhobby

')——意思是:將獲取的資料轉成xml格式,並且取myhobby為行節點名,欄位名為葉子節點名

select * from table for xml path('')——意思是:將獲取的資料轉成xml格式,並且取row為行節點名,欄位名為葉子節點名

select

hobbyid as'

mycode

',hname as'

myname

'from

@hobby

forxml path(

'myhobby

')——意思:改變列節點名 



sql 行列互轉

1 行轉列 現有資料 期望資料 1.1建表建資料 if object id temp 20170701 u is not null drop table temp 20170701 create table temp 20170701 id int primary key identity 1,1 ...

sql行列轉換

問題 如果上述兩表互相換一下 即表結構和資料為 姓名 語文 數學 物理 張三 74 83 93 李四 74 84 94 想變成 得到如下結果 姓名 課程 分數 李四 語文 74 李四 數學 84 李四 物理 94 張三 語文 74 張三 數學 83 張三 物理 93 create table tb ...

SQL 行列轉換

資料列轉換成行。其中一列需要轉換成行,因為列的值不確定所以用動態執行sql sql物件拼寫出要轉換行的列的值。declare sql varchar 1000 select sql isnull sql advertise name from tbl advertise master select ...