Wrox Programmer Forums
Go Back   Wrox Programmer Forums > SQL Server > SQL Server 2000 > SQL Server 2000
|
SQL Server 2000 General discussion of Microsoft SQL Server -- for topics that don't fit in one of the more specific SQL Server forums. version 2000 only. There's a new forum for SQL Server 2005.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Server 2000 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old April 17th, 2004, 02:24 AM
Authorized User
 
Join Date: Jun 2003
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default SQL Query to Convert Columns into Rows

I have a Table which looks like

name, year, value
---------------------
john, 1991, 1000
john, 1992, 2000
john, 1993, 3000
jack, 1991, 1500
jack, 1992, 1200
jack, 1993, 1340
mary, 1991, 1250
mary, 1992, 2323
mary, 1993, 8700
and so on

I want to perform a sql query to return results like this:
year, john, Jack, mary ...
1991, 1000, 1500 1250
1992, 2000, 1200, 2323
1993, 3000, 1340, 8700

Any hint will be greatly appreciated.
 
Old April 19th, 2004, 03:04 AM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 1,212
Thanks: 0
Thanked 1 Time in 1 Post
Default

SELECT [year],
       SUM(CASE WHEN [name]='john' THEN [value] ELSE 0 END) AS john,
       SUM(CASE WHEN [name]='jack' THEN [value] ELSE 0 END) AS jack,
       SUM(CASE WHEN [name]='mary' THEN [value] ELSE 0 END) AS mary
FROM yourTable
GROUP BY [year]
ORDER BY [year]
 
Old April 20th, 2004, 01:36 AM
Authorized User
 
Join Date: May 2003
Posts: 62
Thanks: 0
Thanked 0 Times in 0 Posts
Default

You will have to implement self join on the table.

Deepesh Jain
VB,VBA & .NET Specialist
Wiley Support Team





Similar Threads
Thread Thread Starter Forum Replies Last Post
SQL Query to Convert Columns into Rows Niaz Oracle 3 February 5th, 2010 07:08 AM
SQL Query to convert Columns into Rows....again phix SQL Server 2000 11 November 11th, 2007 09:59 AM
convert columns to rows in sql hoangmv0101 SQL Language 0 January 2nd, 2007 02:04 AM
Formatting sql query rows as columns with stack sastian PHP Databases 0 March 25th, 2005 04:51 AM
getting a query rows as columns raamts SQL Language 1 February 24th, 2005 04:06 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.