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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With