请教SQL写数据透视表,用于数据分析
时间: 2023-02-09 13:19:22 浏览: 72
SQL中使用GROUP BY子句和PIVOT/UNPIVOT操作来实现数据透视表。
基本语法:
```
SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY column1, column2
```
其中aggregate_function可以是SUM, COUNT, AVG等。
例如,要按销售员和商品类别统计销售额,可以使用以下语句:
```
SELECT salesperson, category, SUM(sales)
FROM sales_table
GROUP BY salesperson, category
```
数据透视表可以通过PIVOT操作将行转换为列。
语法:
```
SELECT *
FROM table_name
PIVOT (aggregate_function(column_to_aggregate)
FOR column_to_rotate
IN (list_of_values))
```
例如,要将上面的统计结果转换为以商品类别为行,销售员为列的数据透视表,可以使用以下语句:
```
SELECT *
FROM (
SELECT salesperson, category, SUM(sales)
FROM sales_table
GROUP BY salesperson, category
)
PIVOT (SUM(sales)
FOR salesperson
IN ( 'John', 'Mike', 'Bob'))
```
如果你的数据库不支持pivot 语法,还可以使用CASE 和GROUP BY来实现。