如何在sql中将多行组合成单行

时间:2015-10-29 10:54:46

标签: sql-server sql-server-2008 pivot dynamic-sql dynamic-pivot

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

1 个答案:

答案 0 :(得分:0)

我想你唯一的选择是动态sql,但我建议使用多行表,剩下的就是你的服务器代码(AKA ruby​​,python等)。