SQL SERVER 2008的轉置函式PIVOT

2021-09-06 06:49:22 字數 4123 閱讀 5679

pivot函式用於轉置資料,即用旋轉表的方式把行換成列。pivot可以將表中的列換成行

如下面的例子:

create

table

sales.salesbymonth

(

year

char(4

),

month

char(3

), amount

money

,

primary

key(year,month))

insert

into sales.salesbymonth(year,month

,amount)

values('

2007

','jan

',789.0000

), (

'2007

','feb

',389.0000

), (

'2007

','mar

',8867.0000

), (

'2007

','apr

',778.0000

), (

'2007

','may

',78.0000

), (

'2007

','jun

',9.0000

), (

'2007

','jul

',987.0000

), (

'2007

','aug

',866.0000

), (

'2007

','sep

',7787.0000

), (

'2007

','oct

',85576.0000

), (

'2007

','nov

',855.0000

), (

'2007

','dec

',5875.0000

),

('2008

','jan

',7.0000

), (

'2008

','feb

',6868.0000

), (

'2008

','mar

',688.0000

), (

'2008

','apr

',9897.0000

)

select

year

,

sum(case

when

month='

jan'

then amount else

0end) as

'jan',

sum(case

when

month='

feb'

then amount else

0end) as

'feb',

sum(case

when

month='

mar'

then amount else

0end) as

'mar',

sum(case

when

month='

apr'

then amount else

0end) as

'apr',

sum(case

when

month='

may'

then amount else

0end) as

'may',

sum(case

when

month='

jun'

then amount else

0end) as

'jun',

sum(case

when

month='

jul'

then amount else

0end) as

'jul',

sum(case

when

month='

aug'

then amount else

0end) as

'aug',

sum(case

when

month='

sep'

then amount else

0end) as

'sep',

sum(case

when

month='

oct'

then amount else

0end) as

'oct',

sum(case

when

month='

nov'

then amount else

0end) as

'nov',

sum(case

when

month='

dec'

then amount else

0end) as

'dec

'from

sales.salesbymonth

group

byyear

select

year,[

jan],[

feb],[

mar],[

apr],[

may],[

jun]

,

[jul

],[aug

],[sep

],[oct

],[nov

],[dec

]from

(select

year,amount,month

from sales.salesbymonth) as

salesbymonth

pivot (

sum(amount) for

monthin(

[jan

],[feb

],[mar

],[apr

],[may

],[jun],

[jul

],[aug

],[sep

],[oct

],[nov

],[dec

]))

asourpivot

order

byyear

顯示結果為:

如果去掉year選項,語句改為:

select

[jan

],[feb

],[mar

],[apr

],[may

],[jun],

[jul

],[aug

],[sep

],[oct

],[nov

],[dec

]from

(select amount,month

from sales.salesbymonth) as

salesbymonth

pivot (

sum(amount) for

monthin(

[jan

],[feb

],[mar

],[apr

],[may

],[jun],

[jul

],[aug

],[sep

],[oct

],[nov

],[dec

]))

as ourpivot

則顯示結果:

sqlServer 2008 一行轉多行的問題

前幾天老大發來需求,是要出個報表來著。嗯,就是一行變多行。來貼個簡單的需求 現有如下 要求變成如下 ok,因為有逗號,我首先想到的就是想辦法把逗號去掉。結果發現sql沒有提供像c 那樣split的方法,所以就自己寫了個如下 view code object userdefinedfunction d...

Sql Server 2008 收縮日誌

收縮日誌 alter database dnname set recovery with no wait goalter database dnname set recovery 簡單模式 gouse dnname godbcc shrinkfile n dnname log 11,truncate...

徹底解除安裝sql server2008

微軟的開發工具在按裝和解除安裝時都讓人頭疼,只能是裝在c盤,裝在其他盤時最容易出事 在重新按裝的時候一定要把以前的例項解除安裝完才行。要不就會出錯。在解除安裝sql server後,其實還沒有完成,還要把登錄檔資訊完全刪乾淨,下面就將教您徹底刪除sql server登錄檔的方法,供您參考。在解除安裝...