在postgresql中从多个表中获取数据时获取错误的输出?

时间:2015-06-05 07:28:47

标签: sql postgresql

当我尝试运行此查询时,它提供了错误的输出

SELECT
 (TO_CHAR(sale_order.date_order,'DD')) AS ORDER_DATE,
 (TO_CHAR(sale_order.date_order,'DD-mon-yyyy')),
 SUM(sale_order.amount_total)
FROM
 public.sale_order_line,
 public.product_product,
 public.product_template,
 public.product_category,
 public.sale_order
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
 product_category.name = 'Bboy'
 and
 TO_CHAR(sale_order.date_order,'MON') =  'MAR' --${sale_month} AND
 and
 TO_CHAR(sale_order.date_order,'YYYY') = '2015'  --'${sale_year}

GROUP BY
      (TO_CHAR(sale_order.date_order,'DD-mon-yyyy')),
       (TO_CHAR(sale_order.date_order,'DD'))
ORDER BY
 ORDER_DATE ASC

我认为它会增加行但无法解决。 我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

我使用子查询重写了您的代码。我希望这可以帮助您获取数据而不会增加行数。

SELECT
 (TO_CHAR(sale_order.date_order,'DD')) AS ORDER_DATE,
 (TO_CHAR(sale_order.date_order,'DD-mon-yyyy')),
 SUM(sale_order.amount_total)
FROM
 public.sale_order 
WHERE
 TO_CHAR(sale_order.date_order,'MON') =  'MAR' --${sale_month} AND
 and
 TO_CHAR(sale_order.date_order,'YYYY') = '2015'  --'${sale_year}
 and exists 
    (select product_category.name 
    from 
        public.product_category 
    inner join 
        public.product_template
    on (product_template.categ_id = product_category.id)
    inner join 
        public.sale_order_line
    on (sale_order_line.product_id = product_product.id)
    where
         sale_order.id = sale_order_line.order_id and
        product_category.name = 'Bboy' 
    )

GROUP BY
      (TO_CHAR(sale_order.date_order,'DD-mon-yyyy')),
       (TO_CHAR(sale_order.date_order,'DD'))
ORDER BY
 ORDER_DATE ASC