2012-07-31 42 views
0

我有一个购物车,需要以表格格式列出订单。每个订单可以包含多种产品,每种产品可能有多种选择(这些是书类型产品,您可以选择不同的封面颜色(不收取额外费用),或将您的名字压印在上面(额外收费)1到很多> 1到许多分组/子查询

ERD

我至今是

select 
order_id, 
sum(price_paid * ordered_qty), 
group_concat(product_code SEPARATOR '/') 
from 
orders join order_lines USING (order_id) 
where 
DATE_FORMAT(order_date, '%Y%m') >= '201203' and DATE_FORMAT(order_date, '%Y%m') <= '201203' and order_status = 'SHIPPED' and item_status = 'LINESHIPPED' 
group by order_id 
order by order_id 

这忽略的选项(order_line_options表),并返回此:

58 21.98 SKU-12/SKU-12 
59 10.99 SKU-12 
60 67.78 SKU-31/SKU-12/SKU-56 
61 259.45 SKU-98/SKU-06/SKU-98 
62 9.49 SKU-40/SKU-36 

哪个正确总结的单位成本*数量,并列出一个单列的产品代码(重复的产品代码表示订购不同的选项)

我现在需要的是选项,用于产品的结果是这样的:

58 21.98 SKU-12 (Color: Red, 0.00 - Printname 0.00)/SKU-12 (Color: Blue, 0.00 - Printname 4.95) 

只是SKU-12中所示的一阶蓝色下令两次,一次在红和曾与名字印为$ 4.95

我已经花一天时间/ GROUP_CONCAT和子查询尝试额外的组,但我米甚至没有接近解决方案,所以任何帮助将是伟大的。 Kevin

+0

是否每个line_item_option都填写了所有三个字段? (更具体地说,“Printname”来自哪个字段?) – 2012-07-31 18:37:19

+0

line_item_option可以具有从0到与特定产品关联的任何(但通常为1或2)记录/选项的任何数字。并且sone的成本为零,因此可以忽略,并且需要总结> 0的其他成本。 “打印名称”只是一个示例选项名称(即客户选择他们的名字压在封面上,费用为4.95美元 – KevInSol 2012-07-31 20:02:04

回答

1

您可能会希望在SELECT子句中使用两个相关的子查询。我想以下应该适合你:

select 
order_id, 
sum(price_paid 
    * ordered_qty 
    -- add the cost of any subitems for this line 
    + IFNULL((select sum(option_cost) 
      from order_line_options olo 
     where olo.order_line_id = order_lines.order_line_id),0) 
), 
--Here product_code 
group_concat(
    CONCAT(product_code, 
    ' (', 
    (select group_concat(
      CONCAT(option_name, ': ', 
       option_value, ', ' 
       option_cost 
       ) 
      SEPARATOR '-' 
     ) 
    from order_line_options olo 
    where olo.order_line_id = order_lines.order_line_id 
    group by olo.order_line_id 
    ), 
    ')' 
) -- end of CONCAT() which creates subitem list 
    SEPARATOR '/' 
) 
from 
orders join order_lines USING (order_id) 
where 
    DATE_FORMAT(order_date, '%Y%m') >= '201203' and DATE_FORMAT(order_date, '%Y%m') <= '201203' and order_status = 'SHIPPED' and item_status = 'LINESHIPPED' 
group by order_id 
order by order_id 
+0

谢谢格林联,当您回到办公室时会尝试 – KevInSol 2012-07-31 19:58:41

+0

您可能必须将group_concat在子查询中使用了IFNULL,我不记得CONCAT如何在MySQL中处理NULL值Oracle将它们视为空字符串 – 2012-07-31 23:42:43

+0

非常感谢greenline为您的所有努力 - 它似乎完美工作我刚更改了IFNULL((select sum (option_cost)到IFNULL((select sum(option_cost * ordered_qty))是的,我确实需要IFNULL作为“CONCAT()返回NULL,如果任何参数为NULL”从文档。再次感谢,凯文 – KevInSol 2012-08-01 10:41:06