4

我正在使用 PostgreSQL 数据库并有一个如下表:

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

如您所见,每个日期都有一组指标类型,每种类型都有一个值。我想编写一个 Select 语句,将这些数据组合在下面的庄园中

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

我不确定如何编写此 Select 语句来获得这些结果。任何人都可以帮忙吗?

4

4 回答 4

3

这种数据转换是一个枢纽。如果您的数据库没有数据透视函数,那么您可以使用带有CASE表达式的聚合函数:

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

请参阅带有演示的 SQL Fiddle

结果是:

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

您也可以使用表上的多个连接来执行此操作:

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'

请参阅带有演示的 SQL Fiddle

于 2013-01-16T21:07:50.390 回答
3

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

对于教程,您要查找的内容称为“枢轴” 这也可以使用 CASE 完成,如下所示:http://stackoverflow.com/questions/1241178/mysql-rows-to-columns

于 2013-01-16T21:03:28.070 回答
3

实际上,Postgres确实具有枢轴功能。安装附加模块tablefunc
在此相关问题下查找更多详细信息和解释:
PostgreSQL Crosstab Query

您的查询可能如下所示。假设指标是数据类型integer

SELECT * FROM crosstab(
   'SELECT date, metrictype, metricvalue 
    FROM   tbl
    ORDER  BY 1,2'  -- could also just be "ORDER BY 1" here

   ,$$VALUES ('MetricA'::text), ('MetricB'), ('MetricC')$$)
AS ct ("Section" text, "MetricA" int, "MetricB" int, "MetricC" int);

对于简单的查询,@Bluefeet 演示的CASE语句就可以了。但是对于更长的列列表/更大的表,此查询执行更快并且更短。

于 2013-01-16T23:33:30.030 回答
0
    select a.date as Date,
     a.metric as MetricType ,
b.metric as MetricType ,
     c.metric as MetricType 
    from (select distinct date from yourtable where metric = 'metricA')  a
    join yourtable b on a.date = b.date and b.metric = 'metricB'
    join yourtable c on a.date = c.date and c.metric = 'metricC'
于 2013-01-16T21:08:07.163 回答