【问题标题】:How do i combine multiple rows to single row in sql如何在sql中将多行合并为单行
【发布时间】: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


【解决方案1】:

我猜你唯一的选择是动态 sql,但我的建议是有一个多行表,其余的留给你的服务器代码(AKA ruby​​、python 等)。

【讨论】:

  • 感谢您的回答..但这会给我多个记录集..我希望 test1id 的结果在一行中
  • 什么意思?如果您想在单个列中附加值,您可以为字符串执行value1 + value2
  • SELECT CONCAT(col1, col2, 'just text') AS new_col FROM table
  • (想象 Test2 表有值 Test2ID Test1ID Sectionname FileValidation PostEvent Combined 1 1 Sec1 1 5 1 2 1 Sec2 0 1 1 3 1 Sec3 1 2 1
  • Test1ID CustomerName Sec1FileValidation Sec1PostEvent Sec1Combined Sec2FIleValidation Sec2PostEvent Sec2Combined Sec3Post Sec2Combined Sec3FileValidation 1 Cust1 1 5 1 1 1 2 1 1 这是我所期待的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多