[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 331
  • Last Modified:

Pivot query with values

Sample TableI have a table combined_list and I would like the output to be a pivot output that shows for each unique entry in column 0, to return for each year in column 1 have each value in column 2

For example

PN                         2007            2008       2009

AK801US#ABA      7F                7F           87
AK802US#ABA                          87          88
0
Fairfield
Asked:
Fairfield
2 Solutions
 
Patrick MatthewsCommented:
CREATE TABLE SomeTable([Column 0] varchar(50), [Column 1] int, [Column 3] varchar(50))

INSERT INTO SomeTable([Column 0], [Column 1], [Column 3]) VALUES
('AK810US#ABA', 2007, '7F'),
('AK810US#ABA', 2008, '7F'),
('AK810US#ABA', 2009, '87'),
('AK820US#ABA', 2007, '7F'),
('AK820US#ABA', 2008, '7F'),
('AK820US#ABA', 2009, '87'),
('AK830US#ABA', 2010, '87')

DECLARE @sql varchar(MAX) = 'SELECT t1.[Column 0] AS PN'

SELECT @sql = @sql + ', (SELECT MAX(t2.[Column 3])
    FROM SomeTable t2
    WHERE t2.[Column 0] = t1.[Column 0] AND t2.[Column 1] = ' +
    CONVERT(varchar, [Column 1]) + ') AS [' + CONVERT(varchar, [Column 1]) + ']'
FROM SomeTable
GROUP BY [Column 1]
ORDER BY [Column 1]

SET @sql = @sql + ' FROM SomeTable t1
    GROUP BY t1.[Column 0]
    ORDER BY t1.[Column 0]'

EXEC(@sql)

DROP TABLE SomeTable
0
 
SharathData EngineerCommented:
You can try PIVOT also.
select *
  from SomeTable
pivot (max([Column 3]) for [Column 1] in ([2007],[2008],[2009])) as p

Open in new window


see this example: http://sqlfiddle.com/#!3/2ba3b/1
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now