SQL Row to Column

Source: Internet
Author: User

Purpose: To merge multi-line values of the same condition into the same column.

1. Create a Test table:

CREATE TABLE [dbo].[tb_01](    [SN] [nvarchar]( -)NULL,    [Step_name] [nvarchar]( -)NULL,    [sdate] [datetime] NULL)  on [PRIMARY]


2. Insert the test data:

INSERT  intoTb_01VALUES('V000001','FQC','2015-01-01 10:20')INSERT  intoTb_01VALUES('V000001','OQC','2015-01-02 07:35')INSERT  intoTb_01VALUES('V000002','FQC','2015-05-23 15:26')

3. Raw Data results:

Expected data format:

V000001 FQC (2015-01-01 10:20:00), OQC (2015-01-02-07:35:00)
V000002 FQC (2015-05-23-15:26:00)

4. Using the For XML path implementation:

SELECTSN, Left(Steps,LEN(Steps)-1) asAAAAA from (        SELECTSN, (SELECTStep_name+'('+CONVERT(VARCHAR( -), Sdate, -)+')'+','   fromtb_01WHERESN=a.sn forXML PATH ("')) asSteps fromtb_01 AGROUP  bySN) B

Final Result:

SQL Row to Column

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.