SQL交叉表實(shí)例
很簡單的一個(gè)東西,,見網(wǎng)上好多朋友問“怎么實(shí)現(xiàn)交叉表?”,,以下是我寫的一個(gè)例子,,數(shù)據(jù)庫基于SQL SERVER 2000。 -- ====================================================== --交叉表實(shí)例 -- ====================================================== 建表: 在查詢分析器里運(yùn)行: 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] GO INSERT INTO [test] ([name],[subject],[Source]) values (N‘張三‘,N‘語文‘,60) INSERT INTO [test] ([name],[subject],[Source]) values (N‘李四‘,N‘?dāng)?shù)學(xué)‘,70) INSERT INTO [test] ([name],[subject],[Source]) values (N‘王五‘,N‘英語‘,80) INSERT INTO [test] ([name],[subject],[Source]) values (N‘王五‘,N‘?dāng)?shù)學(xué)‘,75) INSERT INTO [test] ([name],[subject],[Source]) values (N‘王五‘,N‘語文‘,57) INSERT INTO [test] ([name],[subject],[Source]) values (N‘李四‘,N‘語文‘,80) INSERT INTO [test] ([name],[subject],[Source]) values (N‘張三‘,N‘英語‘,100) Go 交叉表語句的實(shí)現(xiàn): --用于:交叉表的列數(shù)是確定的(用了這個(gè)很不錯(cuò)?。?br>select name,sum(case subject when ‘?dāng)?shù)學(xué)‘ then source else 0 end) as ‘?dāng)?shù)學(xué)‘, 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 --用于:交叉表的列數(shù)是不確定的 不確定列,,字段2的值范圍不固定。 create table a (id VARchar(4), F2 VARCHAR(2), F3 INT) insert a(ID,F2,F3) select ‘A001‘,‘01‘,12 UNION ALL SELECT ‘A001‘,‘02‘,24 UNION ALL SELECT ‘A002‘,‘01‘,10 UNION ALL SELECT ‘A002‘,‘03‘,5 UNION ALL SELECT ‘A003‘,‘02‘,6 UNION ALL SELECT ‘A004‘,‘04‘,13 --SELECT * FROM A --不確定列數(shù) declare @sql varchar(8000) set @sql = ‘select ID,‘ select @sql = @sql + ‘sum(case F2 when ‘‘‘ +F2+‘‘‘ then F3 else ‘‘‘‘ end) as ‘‘‘+ ‘字段(‘+F2+‘)‘‘,‘ from (select distinct F2 from A) as B select @sql = left(@sql,len(@sql)-1) + ‘ from A group by ID‘ --PRINT @SQL exec(@sql) go ==============================================================================
交叉表:
CREATE TABLE Test(字段1 VARCHAR(10),字段2 VARCHAR(10),字段3 VARCHAR(10))INSERT Test SELECT ‘a(chǎn)001‘, ‘01‘ , 12 UNION ALL SELECT ‘a(chǎn)001‘, ‘02‘ , 24 UNION ALL SELECT ‘a(chǎn)002‘, ‘01‘ , 10 UNION ALL SELECT ‘a(chǎn)002‘, ‘03‘ , 5 UNION ALL SELECT ‘a(chǎn)003‘, ‘02‘ , 6 UNION ALL SELECT ‘a(chǎn)004‘, ‘04‘ , 13 SELECT * FROM Test SELECT 字段1, [字段(01)]=MAX(CASE WHEN 字段2 =‘01‘ THEN 字段3 ELSE ‘‘ END), [字段(02)]=MAX(CASE WHEN 字段2 =‘02‘ THEN 字段3 ELSE ‘‘ END), [字段(03)]=MAX(CASE WHEN 字段2 =‘03‘ THEN 字段3 ELSE ‘‘ END), [字段(04)]=MAX(CASE WHEN 字段2 =‘04‘ THEN 字段3 ELSE ‘‘ END) FROM Test GROUP BY 字段1 |
|