mysql 为每条数据添加合计列
时间: 2024-02-06 19:08:47 浏览: 19
你可以使用 MySQL 的聚合函数 `SUM()` 来为每条数据添加合计列,具体做法如下:
假设有以下表格 `sales`:
| id | product | quantity | price |
|----|---------|----------|-------|
| 1 | A | 10 | 2.50 |
| 2 | B | 5 | 3.00 |
| 3 | C | 8 | 1.50 |
你可以使用如下 SQL 语句为每条数据添加合计列:
```sql
SELECT id, product, quantity, price, (quantity * price) AS total_price,
(SELECT SUM(quantity * price) FROM sales) AS total_sales
FROM sales;
```
这会返回以下结果:
| id | product | quantity | price | total_price | total_sales |
|----|---------|----------|-------|-------------|-------------|
| 1 | A | 10 | 2.50 | 25.00 | 47.50 |
| 2 | B | 5 | 3.00 | 15.00 | 47.50 |
| 3 | C | 8 | 1.50 | 12.00 | 47.50 |
其中,`total_price` 列是 `quantity * price` 的结果,而 `total_sales` 列是整个表格的销售总额。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)