gpt4 book ai didi

sql - 如何在postgresql中加入两个以上的表?

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

我正在运行以下查询

select 
to_char(sale_order.date_order ,'DD-MM-YYYY') , sum(sale_order.amount_total) as amount

from
public.sale_order
where
sale_order.order_year = '2015' and
sale_order.order_month = 'April'
group by
to_char(sale_order.date_order ,'DD-MM-YYYY') order by to_char(sale_order.date_order ,'DD-MM-YYYY') asc

它给出正确的输出

   to_char..     amount

"14-04-2015"; 1298.00
"15-04-2015"; 4294.00
"16-04-2015"; 1398.00
"17-04-2015"; 1927.00
"18-04-2015"; 3094.00
"19-04-2015"; 6988.00
"20-04-2015"; 6641.00
"21-04-2015"; 3045.00

但我正在尝试输入一个具有多个表连接的条件,然后它会给出不同的金额值

select 
to_char(sale_order.date_order ,'DD-MM-YYYY') , sum(sale_order.amount_total) as amount

from
public.sale_order ,
public.sale_order_line ,
public.product_product ,
public.product_template ,
public.product_category

where
sale_order_line.product_id = product_product.id AND
product_product.product_tmpl_id = product_template.id AND
product_template.categ_id = product_category.id AND
sale_order.id = sale_order_line.order_id AND
sale_order_line.product_id = product_product.id AND
product_product.product_tmpl_id = product_template.id AND
product_template.categ_id = product_category.id AND
product_category.name = 'Starchi' and
sale_order.order_year = '2015' and
sale_order.order_month = 'April'
group by to_char(sale_order.date_order ,'DD-MM-YYYY') order by to_char(sale_order.date_order ,'DD-MM-YYYY') asc

然后它给出不同的输出

  to_char         amount
"14-04-2015"; 1298.00
"15-04-2015"; 4294.00
"16-04-2015"; 1398.00
"17-04-2015"; 2805.00 //wrong output
"18-04-2015"; 6188.00 //wrong output
"19-04-2015"; 13976.00 //wrong output
"20-04-2015"; 19229.00 //wrong output
"21-04-2015"; 3045.00

具体问题是什么,谁能告诉我?

如何解决?

最佳答案

您在 WHERE 子句中犯了一个错误,正如 Gordon Linoff 已经评论过的那样,导致重复的行被检索,然后加起来给出错误的总计。按照 wildplasser 在他的评论中的建议,使用 JOIN 语法更加清晰且不易出错。您的查询将如下所示:

SELECT to_char(o.date_order, 'DD-MM-YYYY') AS "date", sum(o.amount_total) AS amount
FROM public.sale_order o
JOIN public.sale_order_line l ON l.order_id = o.id
JOIN public.product_product pp ON pp.id = l.product_id
JOIN public.product_template pt ON pt.id = pp.product_tmpl_id
JOIN public.product_category pc ON pc.id = pt.categ_id
WHERE pc.name = 'Starchi'
AND o.order_year = '2015'
AND o.order_month = 'April'
GROUP BY o.date_order
ORDER BY o.date_order ASC

关于sql - 如何在postgresql中加入两个以上的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073299/

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