Sql 怎樣將某個列轉為行,實

2021-06-27 19:17:40 字數 3774 閱讀 4384

--如下圖,**的任務就是將圖一轉為圖二

--此功能在pb中的交叉報表也可實現

--編寫此段**是因為今天遇到客戶有這個需求,自己覺得可以挑戰一下,就嘗試做下來了

**如下:

create

table

#patient_result_temp(

patient_code 

nvarchar

(100),

date_test 

datetime,

item_code 

nvarchar

(100),

test_value2 

nvarchar

(100)

) create

table

#patient_result_target(

patient_code 

nvarchar

(100),

date_test 

datetime,

rbc 

nvarchar(50

), wbc 

nvarchar(50

), plt 

nvarchar(50

) )

insert

into

#patient_result_temp 

selecta.

patient_code,a

.date_test,b

.item_code,b

.test_value2 

from

ut_check_patient a

,ut_check_result b 

wherea.

date_test 

=b.test_date 

anda.

ybh 

=b.ybh 

anditem_code in(

'rbc'

,'wbc'

,'plt'

) anda.

date_test 

>

'2013-10-21'

anda.

patient_code 

>''

declare

my_cursor 

cursor

forselect

*from

#patient_result_temp

open

my_cursor

declare

@p_code 

nvarchar

(100

),@d_test 

datetime

,@i_code 

nvarchar

(100

),@t_value2 

nvarchar

(100)

fetch

next 

from

my_cursor 

into

@p_code

,@d_test

,@i_code

,@t_value2

while

(@@fetch_status

=0)begin

if@i_code 

='rbc'

beginif(

select

count

(*) from

#patient_result_target 

where

patient_code 

=@p_code 

anddate_test 

=@d_test

) <=

begin

insert

into

#patient_result_target 

values

(@p_code

,@d_test

,@t_value2,''

,'')

endelse

begin

update

#patient_result_target

setrbc 

=@t_value2

where

patient_code 

=@p_code 

anddate_test 

=@d_test

endend

if@i_code 

='wbc'

beginif(

select

count

(*) from

#patient_result_target 

where

patient_code 

=@p_code 

anddate_test 

=@d_test

) <=

begin

insert

into

#patient_result_target 

values

(@p_code

,@d_test

,@t_value2,''

,'')

endelse

begin

update

#patient_result_target

setwbc 

=@t_value2

where

patient_code 

=@p_code 

anddate_test 

=@d_test

endend

if@i_code 

='plt'

beginif(

select

count

(*) from

#patient_result_target 

where

patient_code 

=@p_code 

anddate_test 

=@d_test

) <=

begin

insert

into

#patient_result_target 

values

(@p_code

,@d_test,''

,'',@t_value2)

endelse

begin

update

#patient_result_target

setplt 

=@t_value2

where

patient_code 

=@p_code 

anddate_test 

=@d_test

endend

fetch

next 

from

my_cursor 

into

@p_code

,@d_test

,@i_code

,@t_value2

endclose

my_cursor

deallocate

my_cursor

select

*from

#patient_result_target 

drop

table

#patient_result_target

drop

table

#patient_result_temp

MySql列轉為行

前一天,在技術群有人提出乙個問題,如下圖所示 問第七題該這麼做?我研究了大概20分鐘左右,這是很典型的將列轉為行的sql。以下是主要步驟 第一步,我建立了表sales drop table ifexists sales create table sales year int 255 default ...

sql 將行顯示為列

比如說,有乙個表 create table tbcoursegrade student varchar 10 course varchar 10 grade int 然後有一些記錄 insert into tbcoursegrade student course grade values 小明 高數...

DataTable將行轉成列

以前一直覺得泛型比較好用,一直沒使用datatable,最近發現泛型也不是萬能的,比如將行轉成列。雖然這種在前台js轉比較方便,但可能也需要這樣的介面,提供別人呼叫,還是記錄一下。將行轉成列 datatable dtresult utility.convertdatatabletovertical ...