SQL Transpose列,具有唯一组合的频率作为新值

时间:2016-08-10 10:52:40

标签: sql postgresql frequency transpose

我正在尝试使用postgresql来汇总一些数据,并且需要生成一个频率列,然后使用频率结果转置另一列。

e.g。 我的起点是这样的:

Month  | Nationality | Car
Oct-15 | GBR         | Rover
Sep-15 | FRA         | Fiat
Oct-15 | GBR         | Rover
Sep-15 | TUR         | Fiat

我想创建一个新列,用于计算其他列的每个唯一组合的频率。所以它想要这样的东西:

Month  | Nationality | Car   | FREQ
Oct-15 | GBR         | Rover | 2
Sep-15 | FRA         | Fiat  | 1
Sep-15 | TUR         | Fiat  | 1

然后我想转置Month列,为Month中的每个值创建新列,并使用频率计数填充这些列的值:

 Nationality | Car    | Sep-15  |  Oct-15
 GBR         | Rover  |   0     |    2 
 FRA         | Fiat   |   1     |    0
 TUR         | Fiat   |   1     |    0

我一直在研究使用数据透视查询和用于转置的交叉表函数,但无法弄清楚如何使用唯一组合的频率作为值来使其工作。

由于

1 个答案:

答案 0 :(得分:1)

一种方法使用条件聚合:

select nationality, car,
       sum(case when month = 'Sep-15' then 1 else 0 end) as "Sep-15",
       sum(case when month = 'Oct-15' then 1 else 0 end) as "Oct-15"
from t
group by nationality, car;

此公式假定month存储为字符串而不是日期。

Postgres确实为此提供了其他功能,例如crosstab。但是,这似乎是您案例中最简单的方法。