SQL Server column forwarding

Source: Internet
Author: User
In this article we will learn how to convert table rows into columns as comma seperated.

-- 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

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
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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.