Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select to combine row values in output table using Pivot or CASE

I am using a PostgreSQL database and have a table as follows:

--------------------------------------
| Date  | MetricType  | MetricValue  |
--------------------------------------
| date1 | MetricA     | val          |
--------------------------------------
| date1 | MetricB     | val          |
--------------------------------------
| date1 | MetricC     | val          |
--------------------------------------
| date2 | MetricA     | val          |
--------------------------------------
| date2 | MetricB     | val          |
--------------------------------------
| date2 | MetricC     | val          |
--------------------------------------

As you can see, each date has a set of metric types and each type has a value. I want to write a Select statement which combines this data in the following manor

------------------------------------------
| Date  | MetricA  | MetricB  | MetricC  | 
------------------------------------------
| date1 | val      | val      | val      |
------------------------------------------
| date2 | val      | val      | val      |
------------------------------------------

I am not sure how to go about writing this Select statement to get these results. Can anyone help?

like image 607
Jordan Ell Avatar asked Jan 14 '23 11:01

Jordan Ell


2 Answers

This data transformation is a pivot. If your database doesn't have a pivot function, then you can use an aggregate function with a CASE expression:

select Date,
  max(case when MetricType = 'MetricA' then MetricValue end) MetricA,
  max(case when MetricType = 'MetricB' then MetricValue end) MetricB,
  max(case when MetricType = 'MetricC' then MetricValue end) MetricC
from yourtable
group by Date

See SQL Fiddle with Demo

The result is:

|  DATE | METRICA | METRICB | METRICC |
---------------------------------------
| date1 |     val |     val |     val |
| date2 |     val |     val |     val |

You can also do this using multiple joins on the table:

select a.date as Date,
 a.MetricValue as MetricA,
 b.MetricValue as MetricB,
 c.MetricValue as MetricC 
from yourtable a
left join yourtable b 
  on a.date = b.date and b.MetricType = 'MetricB'
left join yourtable c 
  on a.date = c.date and c.MetricType = 'MetricC'
where a.MetricType = 'MetricA'

See SQL Fiddle with Demo

like image 52
Taryn Avatar answered Jan 17 '23 03:01

Taryn


See http://www.artfulsoftware.com/infotree/queries.php#78

For a tutorial, what you are looking for is called a "pivot" This can also be done using CASE as shown here:http://stackoverflow.com/questions/1241178/mysql-rows-to-columns

like image 40
Peter Wooster Avatar answered Jan 17 '23 03:01

Peter Wooster