Row record merging in SQL Server

Source: Internet
Author: User

The following columns are available in the table PO: Po#,styel#,color and quantity, where the same po# may have different style#, the same po# and style# may have different color, now the requirement is: po# and style# The color of the same record is calculated with quantity, inserted into a new table, such as:
po# style# Color Quantity
A Red 10
A Blue 20
B Red 10
B Blue 30

To get the table as follows:
po# style# Color Quantity
A Red,blue 30
B Red 10
B Blue 30

You can get all the data you want to insert into the new table as follows:

Select po#,style#, (case COLOR when "then" ELSE Left (Color,len (COLOR)-1) END) color,quantity from (SELECT DISTINCT po#, Style#,colorlist as COLOR, (select SUM (Quantity) from PO WHERE po#=b.po# and style#=b.style#) quantityfrom (select PO #,style#, (SELECT color+ ', ' from PO WHERE po#=a.po# and style#=a.style# for XML PATH (")) as ColorList from P O as A) B) C


Row record merging in SQL Server

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.