Q

Using GROUP BY to collapse rows

Can I get the following with one select statement in SQL?

I have the following:

name    value1 value2 value3
----    ------ ------ ------
tom     1
tom            2
tom                   3
chris          1
ray     6
ray                   0

I want to get the following with one select:

tom,1,2,3
chris,,2,
ray,6,,0

Is this possible and if yes, how?

This is a great example of how to "collapse" rows using the GROUP BY clause.

select name
     , max(value1)
     , max(value2)
     , max(value3)
  from daTable
group
    by name

In SQL, the GROUP BY clause produces one result row for all distinct (combinations of) values of the column(s) mentioned in the GROUP BY clause.

In this particular example, the GROUP BY clause has only one column, name, so the query will produce one result row for every name value. It "collapses" all rows with the same name into one output result row.

The use of the MAX function in the other columns takes advantage of an important feature of aggregate functions, namely that they ignore NULLs. Each column value in the result row—remember, GROUP BY will produce one result row per name—will be the maximum value of all the values in the column, for that name, but ignoring NULLs.

As to the commas which you wanted in the result, you could use SQL string functions to produce them right in the query, but it's better to perform those types of transformations in your application code.

This was first published in May 2007

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close