gpt4 book ai didi

mysql - SQL 查询结果有重复值

转载 作者:行者123 更新时间:2023-11-29 05:07:12 25 4
gpt4 key购买 nike

我有三个表,1.ct_product2.入库3. 缺货

表结构和数据可用here

我想要的输出是

enter image description here

但是我的查询输出是

enter image description here

请问我怎样才能得到我想要的输出?

SQL查询如下

SELECT 
(select product_name from ct_product where id=stock_in.ct_prod_id) as name,
stockin.ct_prod_status,
stockin.ct_prod_catgry,
IFNull(stockin.stock_in, 0) stock_in,
IFNull(stockout.stock_out, 0) stock_out,
IFNull(stockin.stock_in, 0)-IFNull(stockout.stock_out, 0) stockinhand
FROM stock_in
LEFT JOIN
(
SELECT
SUM(quantity) stock_in,
ct_prod_id,
ct_prod_catgry,
ct_prod_status
FROM stock_in
group by ct_prod_catgry, ct_prod_id, ct_prod_status
) stockin ON stockin.ct_prod_id = stock_in.ct_prod_id
LEFT JOIN
(
SELECT
SUM(quantity) stock_out,
ct_prod_id,
ct_prod_catgry,
ct_prod_status
FROM stock_out
group by ct_prod_catgry, ct_prod_id, ct_prod_status
) stockout ON stockout.ct_prod_id = stock_in.ct_prod_id
where stockout.ct_prod_catgry=stock_in.ct_prod_catgry and
stockout.ct_prod_status=stock_in.ct_prod_status

最佳答案

您需要在整体查询上添加一个分组依据,并将 SUM 添加到项目周围以达到总计:

SELECT 
(select product_name from ct_product where id=stock_in.ct_prod_id) as name,
stockin.ct_prod_status,
stockin.ct_prod_catgry,
SUM(IFNull(stockin.stock_in, 0)) stock_in,
SUM(IFNull(stockout.stock_out, 0)) stock_out,
SUM(IFNull(stockin.stock_in, 0)-IFNull(stockout.stock_out, 0)) stockinhand
FROM stock_in
LEFT JOIN
(
SELECT
SUM(quantity) stock_in,
ct_prod_id,
ct_prod_catgry,
ct_prod_status
FROM stock_in
group by ct_prod_catgry, ct_prod_id, ct_prod_status
) stockin ON stockin.ct_prod_id = stock_in.ct_prod_id
LEFT JOIN
(
SELECT
SUM(quantity) stock_out,
ct_prod_id,
ct_prod_catgry,
ct_prod_status
FROM stock_out
group by ct_prod_catgry, ct_prod_id, ct_prod_status
) stockout ON stockout.ct_prod_id = stock_in.ct_prod_id
where stockout.ct_prod_catgry=stock_in.ct_prod_catgry and
stockout.ct_prod_status=stock_in.ct_prod_status
group by name, stockin.ct_prod_status, stockin.ct_prod_catgry

关于mysql - SQL 查询结果有重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45744314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com