SQL交叉表的例項 橫表轉縱表

2021-05-23 01:42:32 字數 2782 閱讀 6037

很簡單的乙個東西,見網上好多朋友問「怎麼實現交叉表?」,以下是我寫的乙個例子,資料庫基於sql server 2000。

交叉表例項

建表:在查詢分析器裡執行:

create table [test] (

[id] [int] identity (1, 1) not null ,

[name] [nvarchar] (50) collate chinese_prc_ci_as null ,

[subject] [nvarchar] (50) collate chinese_prc_ci_as null ,

[source] [numeric](18, 0) null

) on [primary]

goinsert into [test] ([name],[subject],[source]) values (n'張三',n'語文',60)

insert into [test] ([name],[subject],[source]) values (n'李四',n'數學',70)

insert into [test] ([name],[subject],[source]) values (n'王五',n'英語',80)

insert into [test] ([name],[subject],[source]) values (n'王五',n'數學',75)

insert into [test] ([name],[subject],[source]) values (n'王五',n'語文',57)

insert into [test] ([name],[subject],[source]) values (n'李四',n'語文',80) [bitscn.com]

insert into [test] ([name],[subject],[source]) values (n'張三',n'英語',100)

go交叉表語句的實現:

用於:交叉表的列數是確定的

select name,sum(case subject when '數學' then source else 0 end) as '數學',

sum(case subject when '英語' then source else 0 end) as '英語',

sum(case subject when '語文' then source else 0 end) as '語文'

from test

group by name

--用於:交叉表的列數是不確定的

declare @sql varchar(8000)

set @sql = 'select name,'

select @sql = @sql + 'sum(case subject when '''+subject+'''

then source else 0 end) as '''+subject+''','

from (select distinct subject from test) as a

select @sql = left(@sql,len(@sql)-1) + ' from test group by name'

exec(@sql)go

ms server的analysis   services元件是專門用來做交叉表的處理

microsoft   sql   server   2000   analysis   services

自己製作的過程:

create table allen_test(

id number(8,0) not null ,  

name varchar2(30) not null ,  

subject varchar2(30) not null ,  

source number(8,2) ,

primary key (id)  

); comment on column allen_test.id is '序號';

comment on column allen_test.name is '姓名';

comment on column allen_test.subject is '學科';

comment on column allen_test.source is '分數';

insert into allen_test values (1, '張三','語文',60);  

insert into allen_test values (2, '李四','數學',70);  

insert into allen_test values (3, '王五','英語',80);   

insert into allen_test values (4, '王五','數學',75);  

insert into allen_test values (5, '王五','語文',57);  

insert into allen_test values (6, '李四','語文',80) ;  

insert into allen_test values (7, '張三','英語',100);

select name,

sum(case subject when '數學' then source else 0 end) as 數學,  

sum(case subject when '英語' then source else 0 end) as 英語,  

sum(case subject when '語文' then source else 0 end) as 語文  

from allen_test  

group by name;

縱表轉橫表sql

縱表結構 fname ftype fvalue 小明 zaocan 10 小明 zhongcan 20 小明 wancan 5 轉換後的表結構 fname zaocan value zhongcan value wancan value 小明 10 20 5 縱表轉橫表sql如下 select fn...

縱表轉橫表的 SQL 示例

縱表轉橫表的 sql 示例 縱表結構 fname ftype fvalue 小喬 zaocan 10 小喬 zhongcan 20 小喬 wancan 5 轉換後的表結構 fname zaocan value zhongcan value wancan value 小喬 10 20 5 縱表轉橫表s...

縱表轉橫表簡單的sql

縱表結構 fname ftype fvalue 小明 zaocan 10 小明 zhongcan 20 小明 wancan 5 轉換後的表結構 fname zaocan value zhongcan value wancan value 小明 10 20 5 縱表轉橫表sql如下 select fn...