SQL行轉列例項

2021-06-16 02:15:00 字數 2057 閱讀 9365

sql行轉列是比較經典的問題:

比如有如下資料表,有如下某一款號(表1):

顏色  尺碼  庫存 

紅色    s    10

紅色    m    80

白色    l    50

白色    s    60

要將上面的表轉化為如下格式(表2): 

顏色    s  m  l

紅色  10  80  0 

白色  60  0  50

動態sql:

create

table

#tbl_0

(color

nvarchar(12

),nsize

nchar(1

),store

int)

insert

into

#tbl_0

select

'red

',    's

',    '10

'union

allselect

'red

',    'm

',    '80

'union

allselect

'white

',    'l

',    '50

'union

allselect

'white

',    's

',    '60

'select

*from

#tbl_0

--結果

--red    s    10

--red    m    80

--white    l    50

--white    s    60

declare

@sql

varchar

(4000

)set

@sql='

select color,

'select

@sql

=@sql+'

isnull(sum(case nsize when

'''+ns+

'''then isnull(store,0) end),0)

'''+ns+

''',

'from

(select's

'asns union

allselect'm

'union

allselect'l

') a

set@sql

=stuff

(@sql

,len

(@sql),1

,'')set

@sql

=@sql+'

from #tbl_0 group by color

'exec

(@sql)--

結果--

red    10    80    0

--white    60    0    50

drop

table

#tbl_0

靜態sql:

select

color,

isnull

(sum

(case

nsize

when's

'then

isnull

(store,0)

end),0)

's',

isnull

(sum

(case

nsize

when'm

'then

isnull

(store,0)

end),0)

'm',

isnull

(sum

(case

nsize

when'l

'then

isnull

(store,0)

end),0)

'l'from

#tbl_0

group

bycolor

資料行轉列例項

在系統開發中常常遇到進行資料的統計,並將資料行轉列的情景,例如表中的表示。但是在資料庫中呈現出來的資料往往是橫行的樣式。這就需要乙個轉換。轉換的方式有兩種方式。1.利用cross join去進行轉換。2.利用case when函式去轉換。資料庫查詢出的結果 張三170 李四90 王五180 需要資料...

行轉列技巧例項

insert into goods temp select a.goods id,a.bn as 商品編碼,a.name as 商品名稱,a.common name as 通用名,i.manufacturer as 生產廠家,a.cfproperty 處方分類,a.valid period as 有...

sql 行轉列問題

題目 下表tproduct某產品在各城市各月銷量情況 city name month no 月 qut qty 臺 杭州 9 100 杭州 10 120 上海 9 130 上海 10 140 請寫sql實現 如下查詢 city 9月銷量 10月銷量 杭州 100 120 上海 130 140 答案一...