postgre不采用函数进行行转列的案例
时间: 2024-01-02 13:02:08 浏览: 82
Oracle迁postgre 不兼容字段、函数等更改
在PostgreSQL中,可以使用crosstab函数将行转换为列,但也可以使用其他方法实现相同的功能。以下是一个不使用函数将行转换为列的例子:
假设有以下表格:
```
CREATE TABLE sales (
id serial PRIMARY KEY,
month text,
revenue integer
);
INSERT INTO sales (month, revenue)
VALUES ('January', 1000),
('February', 1500),
('March', 2000),
('April', 2500);
```
可以使用以下查询将月份列转换为行:
```
SELECT
SUM(CASE WHEN month = 'January' THEN revenue ELSE 0 END) AS "January",
SUM(CASE WHEN month = 'February' THEN revenue ELSE 0 END) AS "February",
SUM(CASE WHEN month = 'March' THEN revenue ELSE 0 END) AS "March",
SUM(CASE WHEN month = 'April' THEN revenue ELSE 0 END) AS "April"
FROM sales;
```
输出结果为:
```
January | February | March | April
---------+----------+-------+-------
1000 | 1500 | 2000 | 2500
```
这个查询使用了CASE语句来创建新的列,如果月份匹配,则为该月份的销售额,否则为0。然后使用SUM函数将每个月份的销售额相加。
阅读全文