如果不是将圆珠笔放在同一行的话,lz可以参考看看http://bbs.csdn.net/topics/320026119
解决方案 »
- SQL的系统函数,像isNull这样的函数是如何实现的,我在那能看到代码吗?
- 重复记录删除问题
- 如何从Sql Server导出数据到Excel/Access?我已经实现(Access->excel,excel->sql server)(纯SQL语句实现)
- 如何获取返回值?
- 重新写顺序号
- 请问:用SQL语句可以将ACCESS中的表全部导入到SQL SERVER2000中吗?
- 关于VFP的问题!!!
- Access导入到SQL,是不是不能导入ID字段的吗?
- 怎样禁用 MS SQL 2005的windows身份验证
- 请问我的是win10系统,安装了个mssql数据库,用的系统帐号是Test,后来我删除了,用Administrator进去,数据库就死活进不去了
- win7 64位,在ODBC的DNS中对sql server配置成功,但连接失败
- 如何建立一个课程表
多行的时候在后面自动添加列,
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-16 12:26:42
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([种类] varchar(6),[厂家] varchar(1),[价格] int,[规格型号] varchar(2))
insert [huang]
select '铅笔','A',10,'2B' union all
select '铅笔','B',20,'HB' union all
select '圆珠笔','C',15,'SB'
--------------开始查询--------------------------declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([种类]+'厂家')+'=max(case when [种类]='+quotename([种类],'''')+' and [厂家]='+quotename(厂家,'''')+' then [厂家] else null end)'
+','+quotename([种类]+'价格')+'=max(case when [种类]='+quotename([种类],'''')+' and [厂家]='+quotename(厂家,'''')+' then [价格] else null end)'
+','+quotename([种类]+'规格型号')+'=max(case when [种类]='+quotename([种类],'''')+' and [厂家]='+quotename(厂家,'''')+' then [规格型号] else null end)'
from [huang]
SET @s=SUBSTRING(@s,2,LEN(@s))
exec('select '+@s+' from [huang] ')
----------------结果----------------------------
/*
铅笔厂家 铅笔价格 铅笔规格型号 铅笔厂家 铅笔价格 铅笔规格型号 圆珠笔厂家 圆珠笔价格 圆珠笔规格型号
---- ----------- ------ ---- ----------- ------ ----- ----------- -------
A 10 2B B 20 HB C 15 SB
*/
试试这个:
--drop table test
--gocreate table test(种类 varchar(10), 厂家 varchar(10), 价格 int, 规格型号 varchar(10))insert into test
select '铅笔', 'A' ,10 ,'2B' union all
select '铅笔', 'B' ,20 ,'HB' union all
select '圆珠笔', 'C' ,15 ,'SB' union all
select '圆珠笔', 'd' ,15 ,'xx'
go
declare @sql varchar(8000)set @sql = ''select @sql = @sql +
',max(case when 厂家='''+厂家+''' then 厂家 else null end) ['+种类+'厂家'+
case when rownum = 1 then '' else CAST(rownum as varchar) end+']'+
',max(case when 价格='+cast(价格 as varchar)+' then 价格 else null end) ['+种类+'价格'+
case when rownum = 1 then '' else CAST(rownum as varchar) end+']'+
',max(case when 规格型号='''+规格型号+''' then 规格型号 else null end) ['+种类+'规格型号'+
case when rownum = 1 then '' else CAST(rownum as varchar) end+']'
from
(
select *,
ROW_NUMBER() over(PARTITION by 种类 order by getdate()) rownum
from test
)tselect @sql = 'select '+STUFF(@sql,1,1,'') +
' from
(
select *,
ROW_NUMBER() over(PARTITION by 种类 order by getdate()) rownum
from test
)t'
exec(@sql)
/*
铅笔厂家 铅笔价格 铅笔规格型号 铅笔厂家2 铅笔价格2 铅笔规格型号2 圆珠笔厂家 圆珠笔价格 圆珠笔规格型号 圆珠笔厂家2 圆珠笔价格2 圆珠笔规格型号2
A 10 2B B 20 HB C 15 SB d 15 xx
*/