sql server 列转行
来源:未知 责任编辑:责任编辑 发表时间:2013-08-27 11:18 点击:次
两个表
表1:tb_Site
CREATE TABLE [dbo].[tb_Site] (
[sid] [int] IDENTITY (1, 1) NOT NULL ,
[sname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
表2:tb_qx
CREATE TABLE [dbo].[tb_qx] (
[qid] [int] IDENTITY (1, 1) NOT NULL ,
[qname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
动态SQL
declare @sql1 varchar(8000)
set @sql1='select c.sname '
select @sql1=@sql1+', max(case qname when'''+qname+'''then qname else ''0'' end) ['+qname+']' from tb_qx
select @sql1=@sql1+' from (select * from tb_Site left join (select * from tb_qx) d on 1=1) c group by c.sname'
exec(@sql1)
摘自 李晓光的专栏
表1:tb_Site
CREATE TABLE [dbo].[tb_Site] (
[sid] [int] IDENTITY (1, 1) NOT NULL ,
[sname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
表2:tb_qx
CREATE TABLE [dbo].[tb_qx] (
[qid] [int] IDENTITY (1, 1) NOT NULL ,
[qname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
动态SQL
declare @sql1 varchar(8000)
set @sql1='select c.sname '
select @sql1=@sql1+', max(case qname when'''+qname+'''then qname else ''0'' end) ['+qname+']' from tb_qx
select @sql1=@sql1+' from (select * from tb_Site left join (select * from tb_qx) d on 1=1) c group by c.sname'
exec(@sql1)
摘自 李晓光的专栏
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>