类型 数量 姓名
a 1 张三
a 2 李四
b 2 李四
b 2 张三
c 3 张三
c 3 李四
d 4 李四
d 4 张三
e 5 张三
e 5 李四
结果
姓名 a b c d e
-------------------------------------
张三 1 2 3 4 5
李四 2 2 3 4 5
类型不固定,请问应该怎么写sql语句
a 1 张三
a 2 李四
b 2 李四
b 2 张三
c 3 张三
c 3 李四
d 4 李四
d 4 张三
e 5 张三
e 5 李四
结果
姓名 a b c d e
-------------------------------------
张三 1 2 3 4 5
李四 2 2 3 4 5
类型不固定,请问应该怎么写sql语句
解决方案 »
- SQL递归来取得树型目录下的数据
- mssql © 版权符号乱码
- 超时时间已到。在操作完成之前超时时间已过或服务器未响应。
- 雷人~!一多汗~!看看这SQLAGENT
- 请教如何对SQL SERVER备份的数据库文件加密
- 关于日期转换的问题,求指教。
- 求一条语句改变列值
- 关于 Select * from table where column not in(...)
- 请问 我把excel表import到sql-server里面,字符型字段怎么变成nvarchar(256)太大了??
- 不用临时表,游标,单用SQL,能实现这样的查询吗?
- 国外vps服务器地址本地不能打开,外地却能打开
- 行转列问题,求帮助
insert into tb
select 'a', 1, '张三' union all
select 'a', 2, '李四' union all
select 'b', 2, '李四' union all
select 'b', 2, '张三' union all
select 'c', 3, '张三' union all
select 'c', 3, '李四' union all
select 'd', 4, '李四' union all
select 'd', 4, '张三' union all
select 'e', 5, '张三' union all
select 'e', 5, '李四' union all
select 'f', 1, '张三' union all
select 'f', 1, '张三' union all
select 'g', 1, '张三' union all
select 'g', 1, '张三'
DECLARE @SQL VARCHAR(8000)
SELECT @SQL = ISNULL(@SQL + '],[' , '') + 类型 FROM tb GROUP BY 类型
SET @SQL = '[' + @SQL + ']'
EXEC('
SELECT *
FROM (
SELECT *
FROM tb
) A PIVOT (MAX(数量) FOR 类型 IN (' + @SQL + ')) B'
)
drop table tb--------------------------------------------------------
姓名 a b c d e f g
---------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
李四 2 2 3 4 5 NULL NULL
张三 1 2 3 4 5 1 1
name,
max(case 类型 when 'a' then 数量 else 0 end) as 'a',
max(case 类型 when 'b' then 数量 else 0 end) as 'b',
max(case 类型 when 'c' then 数量 else 0 end) as 'c',
max(case 类型 when 'd' then 数量 else 0 end) as 'd',
max(case 类型 when 'e' then 数量 else 0 end) as 'e'
from
tb
group by
name
create table tb(类型 varchar(1),数量 int,姓名 varchar(10))insert into tb
select 'a', 1, '张三' union all
select 'a', 2, '李四' union all
select 'b', 2, '李四' union all
select 'b', 2, '张三' union all
select 'c', 3, '张三' union all
select 'c', 3, '李四' union all
select 'd', 4, '李四' union all
select 'd', 4, '张三' union all
select 'e', 5, '张三' union all
select 'e', 5, '李四'
declare @sql varchar(2000)select @sql='select 姓名,'select @sql=@sql+'sum(case 类型 when '''+类型+''' then 数量 else 0 end) as '''+类型+''','
from (select distinct 类型 from tb) yselect @sql=left(@sql,len(@sql)-1)select @sql=@sql+' from tb group by 姓名 order by 姓名 desc'exec(@sql)姓名 a b c d e
---------- ----------- ----------- ----------- ----------- -----------
张三 1 2 3 4 5
李四 2 2 3 4 5