-- Create a table variable to store user data
DECLARE @myTable TABLE
(
UserName VARCHAR(50),
ArticleName VARCHAR(50)
)

-- Insert some data to table to work on that data
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('Jack', 'ASP.NET')
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('Jack', 'SQL Server')
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('Jack', 'C#')
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('Jack', 'VB.NET')

INSERT INTO @myTable(UserName, ArticleName)
VALUES ('David', 'Java')
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('David', 'Java Beans')
INSERT INTO @myTable(UserName, ArticleName)
VALUES ('David', 'Java script')

SELECT UserName, ArticleName FROM @myTable

-- This is how the table looks after inserting the data
SQLSERVER列转行

Now I want all the articles related to Jack and David in a single column.
This how we can achieve this

-- Cross join each user with his article. By cross joining we will get all the articles for each user
SELECT DISTINCT A.UserName,Articles FROM @myTable A
CROSS APPLY
(
-- Now get all the articles for each author in XML
SELECT ArticleName + ', ' FROM @myTable B WHERE A.UserName = B.UserName
FOR XML Path('')
) AS C (Articles)

The output of the below query is shown below.

-- By applying cross join I can able to get all the articles related with Jack and David.
SQLSERVER列转行

相关文章:

  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
  • 2021-07-05
  • 2022-01-07
猜你喜欢
  • 2022-12-23
  • 2022-02-03
  • 2022-12-23
  • 2022-01-06
  • 2021-07-26
  • 2021-08-23
  • 2022-02-23
相关资源
相似解决方案