SQL 转置列,将唯一组合的频率作为新值

SQL Transpose column, with frequencies of unique combinations as new values

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

例如 我的起始table是这样的:

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

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

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

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

谢谢

一种方法使用条件聚合:

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。但是,对于您的情况,这似乎是最简单的方法。