Postsum SQL汇总中的DISTINCT vs CASE语句

时间:2019-02-02 04:09:00

标签: postgresql

我有一个SQL查询,该查询使用DISTINCT来汇总可归为集合(每个集合= 1且被计数一次)或使用inventory_type属性进行整体分类的一类物品的成本。下面的查询在大多数情况下很好地总结了这些属性:

(sum(distinct product_working_value_SET)+sum(product_working_value_WHOLE)) working_cost_category

  FROM (select
      case inventory_type when 'set' then product_working_value else 0 end as product_working_value_SET,
      case inventory_type when 'whole' then product_working_value else 0 end as product_working_value_WHOLE
  )

当我有两套价格相同的不同套装时,就会出现问题。该查询无法将其识别为不同的内容,因此会跳过它,并给出不正确的总和。我唯一可以使用的可靠区分是product_nameproduct_id;在这种情况下,集更有可能具有不同的命名。我可以重做以说明这种特异性吗?

下面是一个示例类别数据集,其中包含报告的值和期望值(同样,每个集合均应计为一个):

        Name    Inventory Type  Working Cost $
    Blue & Gold King Bed Set    Set $480.00
    Blue & Gold King Bed Set    Set $480.00
    Floral Bed Set  Set $240.00
    King Blue and White Floral Bed Set  Set $240.00
    King Blue and White Floral Bed Set  Set $240.00
    King Orange Comforter Set   Set $168.00 <<< same price
    King Orange Comforter Set   Set $168.00
    King Orange Comforter Set   Set $168.00
    King Orange Comforter Set   Set $168.00
    King Orange Comforter Set   Set $168.00
    King Orange Comforter Set   Set $168.00
    Red Queen Set   Set $60.00
    Red Queen Set   Set $60.00
    Red Queen Set   Set $60.00
    White King Comforter Set    Set $168.00 <<< same price coincidentally again
    White King Comforter Set    Set $168.00
    White King Comforter Set    Set $168.00
    White King Comforter Set    Set $168.00
    White King Comforter Set    Set $168.00

working_cost_category: reported:          $990.00
                       audit calculation: $1158 (168 missing)

0 个答案:

没有答案