【发布时间】:2015-10-29 10:54:45
【问题描述】:
CREATE TABLE [dbo].[Table1](
[Table1ID] [int] IDENTITY(1,1) NOT NULL,
[CreateDate] [datetime] NOT NULL,
[CreatedByUserID] [int] NOT NULL,
[Customer] varchar(50) NOT NULL,
CONSTRAINT [PK_dbo.Table1] PRIMARY KEY CLUSTERED
(
[Table1ID] ASC
))
SET IDENTITY_INSERT [dbo].table1 on
insert into table1 ([Table1ID] , [CreateDate] , [CreatedByUserID] , [Customer] )values(1,GETDATE(),1,'customer1'),(2,GETDATE(),1,'customer1'),(3,GETDATE(),1,'customer1'),(4,GETDATE(),1,'customer1')
SET IDENTITY_INSERT [dbo].table1 off
CREATE TABLE [dbo].[Table2](
[Table2ID] [int] IDENTITY(1,1) NOT NULL,
[Table1ID] [int] NOT NULL,
[ActualData] [nvarchar](255) NULL,
[BoolCol1] [bit] NOT NULL,
[IntCol] [int] NULL,
[BoolCol2] [bit] NULL,
[BoolCol3] [bit] NOT NULL,
[BoolCol4] [bit] NOT NULL,
[BoolCol5] [bit] NOT NULL,
CONSTRAINT [PK_dbo.Table2] PRIMARY KEY CLUSTERED ( [Table2ID] ASC))
ALTER TABLE [dbo].[Table2] WITH CHECK ADD
CONSTRAINT [FK_dbo.Table2_dbo.Table1_Table1ID] FOREIGN KEY([Table1ID])
REFERENCES [dbo].[Table1] ([Table1ID])
SET IDENTITY_INSERT [dbo].table2 on
insert into table2
([Table2ID] , [Table1ID] , [ActualData] , [BoolCol1] , [IntCol] , [BoolCol2] , [BoolCol3] , [BoolCol4] , [BoolCol5] )
values (1,1,'Value 1',1,10,0,1,1,1),(2,1,'Value 2',0,20,1,1,1,0),(3,1,'Value 3',0,30,1,1,1,1),(4,1,'Value 4',0,40,1,1,1,0),(5,1,'Value 5',0,50,1,1,1,1)
SET IDENTITY_INSERT [dbo].table2 off
同样,我有大约 5 个表需要加入并从所有列中获取数据...我可以得到类似于下面的结果吗
Table1ID CreatedDate CreatedByUserID,Customer1 Value1 BoolCol1 Value1 IntCol1 Value1 BoolCol2 Value1 BoolCol3 Value1 BoolCol4 Value1 BoolCol5 Value2 BoolCol1 Value2 IntCol1 Value2 BoolCol2 Value2 BoolCol3 Value2 BoolCol4 Value2 BoolCol5 Value3... Value3 Int
1 01-01-2015' 1 customer1 1 10 0 1 1 1 0 20 1 1 1 0 0 30
【问题讨论】:
-
或者如果你需要多列,那么这里是你的副本:stackoverflow.com/questions/10404348/…
-
Tab Alleman :该链接谈到仅显示一列的结果。就我而言,我有很多列需要在 PIVOT 之后显示
-
然后看我的第二条评论,它是针对动态枢轴的。
-
我没有你的数据,所以我无法想象你对一列和其他列的意思。您能否发布一个示例,说明您从发布的代码中获得的结果以及您想要获得的结果?
标签: sql-server sql-server-2008 pivot dynamic-sql dynamic-pivot