【发布时间】:2015-07-16 09:17:13
【问题描述】:
我正在运行以下查询
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
请问具体的问题是什么?
以及如何解决?
【问题讨论】:
-
问题是你的连接增加了行数。 Postgres 工作正常。问题要么是你的数据,要么是你对数据的理解。
-
我该如何解决这个问题,它可能会添加一行 sale_order 和 sale_order_line
-
我首先将查询重写为连接语法。然后:注释掉所有未使用的表(特别是:
order_line)。另外:不需要在to_char()上进行聚合,原始 date_order 上的聚合也可以正常工作。
标签: sql postgresql postgresql-9.2 odoo pgadmin