如何通过产品ID获取不同的状态计数

时间:2019-01-22 10:34:08

标签: mysql sql oracle mysqli

我从下面的一个复杂查询中得到了结果

SELECT o_items.sku,
       o_items.name        AS 'title',
       o_items.qty_ordered AS 'quantity',       
       s_orders.base_amount_paid AS 'paid/unpaid'
  FROM sales_order_payment s_orders
 INNER JOIN (SELECT s.sku, s.name, s.qty_ordered, s.order_id
               FROM sales_order_item s             
              INNER JOIN (SELECT p.entity_id
                           FROM catalog_product_entity AS p                         
                          INNER JOIN catalog_product_entity_int AS a
                             ON p.row_id = a.row_id
                          WHERE VALUE >= 0
                            AND                               
                                a.attribute_id =
                                (SELECT attribute_id
                                   FROM eav_attribute                                 
                                  WHERE attribute_code = 'is_darkhorse')) as q
                 ON s.product_id = q.entity_id             
              WHERE s.created_at BETWEEN '2019-01-14' AND '2019-01-16') o_items
          ON
             s_orders.parent_id = o_items.order_id

enter image description here 这是已付款或尚未付款的订单数据。金额代表已付款,空值代表未付款状态

我正在尝试生成以下结果,但无法成功,需要帮助。实际上,此结果显示了如何支付一定数量的产品以及尚未支付多少数量。这将是上述获取的数据的结果。 enter image description here

请指导我如何继续获得这些结果。

2 个答案:

答案 0 :(得分:1)

使用它。 ...代表现有代码。

select .... , sum(case  when s_orders.base_amount_paid  is not null 
                        then o_items.qty_ordered
                        else 0 
                  end) as paid, 
              sum(case  when s_orders.base_amount_paid  is null 
                        then o_items.qty_ordered 
                        else 0 
                  end) as unpaid
From .......

答案 1 :(得分:0)

您可以一起使用ififnull函数(假定您使用mysql作为DBMS

GROUP BY表达式

SELECT c.sku, c.name, 
       sum(if(ifnull(base_amount_paid,0)=0,0,1)) as paid,
            sum(if(ifnull(qty_ordered,0)=0,0,1)) as unpaid
  FROM catalog_prod_ent_derived c
 GROUP BY c.sku, c.name

其中catalog_prod_ent_derived将整个查询表示为子查询。