编写mysql脚本,计算不同产品每日进销存,输出日期,产品,进货量,出库量,日累计结余;一张表有日期,产品,进货量;另一张表有日期,产品,出库量
时间: 2023-12-11 22:06:13 浏览: 26
好的,下面是一个MySQL脚本,可以计算不同产品每日进销存,输出日期、产品、进货量、出库量和日累计结余:
```sql
SELECT
COALESCE(purchases_table.date, sales_table.date) AS date,
COALESCE(purchases_table.product, sales_table.product) AS product_id,
IFNULL(purchases_table.quantity, 0) AS total_purchases,
IFNULL(sales_table.quantity, 0) AS total_sales,
SUM(IFNULL(purchases_table.quantity, 0) - IFNULL(sales_table.quantity, 0))
OVER (PARTITION BY COALESCE(purchases_table.date, sales_table.date),
COALESCE(purchases_table.product, sales_table.product)
ORDER BY COALESCE(purchases_table.date, sales_table.date)) AS daily_inventory
FROM
purchases_table
FULL OUTER JOIN
sales_table ON purchases_table.product = sales_table.product
AND purchases_table.date = sales_table.date
ORDER BY
date, product_id;
```
这个脚本假设你的数据是存储在两张表中:`purchases_table`和`sales_table`。这两个表都包含以下列:
- `product`:产品ID;
- `date`:日期;
- `quantity`:进货量或出库量。
脚本使用了全外连接(FULL OUTER JOIN)来将进货量和出库量进行合并。然后它按照日期和产品ID进行排序,并计算每日的进销存情况。注意,这里使用了窗口函数(OVER),以便计算每个日期和产品组合的日累计结余。COALESCE函数用于处理那些只在一个表中出现的日期或产品的情况。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)