Original Structure
Column1 column2
---------------------
1
1 B
2 C
2 D
2 E
3 F
Query results:
Column1 column2
-----------------------------
1 A, B
2 C, D, E
3 F
Concatenate column2 of column1 rows into one column.
I wonder how to describe this usage. Is there a mature professional title for cross-table and cross-table related conventions?
Can it also be called another cross-table?
This requirement should be common. There are also many demos on the Internet, which are now simple to implement for reference. -- Example of connecting multiple rows and multiple columns into a single row and Single Column: a user-defined function is required.
If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [verttohorzsample] ') and objectproperty (ID, n' isusertable') = 1)
Drop table [DBO]. [verttohorzsample]
Go
-- Create Test Data
Create Table verttohorzsample (
Column1 int,
Column2 varchar (100)
)
Go
Insert into verttohorzsample (column1, column2)
Select 1, 'A'
Union all
Select 1, 'B'
Union all
Select 2, 'C'
Union all
Select 2, 'D'
Union all
Select 2, 'E'
Union all
Select 3, 'F'
Go
If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [convertverttohorz] ') and xtype in (n'fn', n'if', n'tf '))
Drop function [() function [DBO]. [convertverttohorz]
Go
-- Create auxiliary functions
Create Function convertverttohorz () function convertverttohorz (@ col1val INT)
Returns varchar (8000)
As
Begin
-- In the actual project, check whether @ retval contains more than 8000 characters.
Declare @ retval varchar (8000)
Set @ retval =''
-- Store a specified column to a temporary variable through recursive select connection
Select @ retval = column2 + ',' + @ retval from verttohorzsample where column1 = @ col1val
-- Connect multiple columns
-- Select @ retval = column2 + ',' + column3 + ',' + column4 + ',' + @ retval from verttohorzsample where column1 = @ col1val
-- Remove the tail, (comma)
If Len (@ retval)> 0
Set @ retval = left (@ retval, Len (@ retval)-1)
-- Print @ retval
Return @ retval
End
Go
-- Test
Select column1, DBO. convertverttohorz (column1) column2 from (select distinct column1 from verttohorzsample) T
/**//*
Column1 column2
-----------------------------
1 A, B
2 C, D, E
3 F
*/
Go
If exists (select * From DBO. sysobjects where id = object_id (n' [DBO]. [verttohorzview] ') and objectproperty (ID, n' isview') = 1)
Drop view [DBO]. [verttohorzview]
Go
-- Create a view
Create view DBO. verttohorzview
As
Select column1, DBO. convertverttohorz (column1) column2
From (select distinct column1 from DBO. verttohorzsample) T
Go
-- Test View
Select * From verttohorzview
/**//*
Column1 column2s
----------------------------
1 A, B
2 C, D, E
3 F
*/