|
Oracle General Oracle database discussions. |
Welcome to the p2p.wrox.com Forums.
You are currently viewing the Oracle 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
|
|
|
April 17th, 2004, 02:19 AM
|
Authorized User
|
|
Join Date: Jun 2003
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
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.
|
April 17th, 2004, 01:30 PM
|
Authorized User
|
|
Join Date: Jul 2003
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Hi Niaz,
You can accomplish this by a "pivot" query. Please look at the small testcase that I prepared below:
SQL> desc t1
Name Null? Type
--------------- -------- ----------------
NAME VARCHAR2(10)
YEAR NUMBER(4)
VALUE NUMBER(4)
SQL>
SQL> select * from t1;
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
9 rows selected.
SQL> -- now, try out the pivot query
SQL> select year,
2 max( decode( name, 'john', value, null ) ) "JOHN",
3 max( decode( name, 'jack', value, null ) ) "JACK",
4 max( decode( name, 'mary', value, null ) ) "MARY"
5 from
6 (
7 select name, year, value
8 from t1
9 )
10 group by year ;
YEAR JOHN JACK MARY
---------- ---------- ---------- ----------
1991 1000 1500 1250
1992 2000 1200 2323
1993 3000 1340 8700
SQL>
Hope that helps.
Cheers,
Prat
|
April 18th, 2004, 12:04 AM
|
Authorized User
|
|
Join Date: Jun 2003
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Thanks Prat.
I also created a similar Query using DECODE and GROUP BY.
Regards
Niaz
|
February 5th, 2010, 07:08 AM
|
Registered User
|
|
Join Date: Feb 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Hey
Hi,
I have a similar requirement, the only constraint being the fact that I have Strings instead of integers. So, the max() will not work.
Is there a way around that ?
Thanks
|
|
|