SQL- Summing Case/When values from different fields

被刻印的时光 ゝ 提交于 2020-01-07 02:55:28

问题


I am trying to SUM values generated from a CASE/WHEN statement. The only problem is that the values come from different fields.

Example:

This is a set of overhead values from one item out of many in my query. In this example, I need to SUM the overhead values 14.850000 and 1.166600 to 16.016.
The vac_type column determines the type of costs. In this case, when vac_type = WO1 or WO2, they are overhead costs. W10 is not, thus the NULL value.

In all, there are 12 vac_types that are overhead values. They are all listed in my CASE/WHEN statement. I need to SUM all of these overhead values by item_no, but since the vac_type field has two different values, my query considers them DISTINCT from each other and unable to be summed.

This is my unsuccessful attempt to SUM Overhead by item_no. It generates the list in which the screenshot above comes from:

SELECT DISTINCT 'Overhead' =  SUM(CASE
                          WHEN vac_type IN('A01', 'AD0', 'ADX', 'A01', 'CI0', 'DO1', 'DP9',
                          'O20', 'PWO', 'TO1', 'WO1', 'WO2')
                     THEN (Cost_Values)
                     ELSE NULL
                     END,
         item_no,
         comp_item,
         vac_type

FROM     table_1

GROUP BY item_no,
         comp_item,
         vac_type

回答1:


Thank you to @Lamak for answering. In order to SUM overhead by item_no, any unique fields need to be removed from the SELECT and GROUP BY statement. By removing vac_type, I got the data I needed.

SELECT 'Overhead' = Sum(CASE
                      WHEN vac_type IN ( 'A01', 'AD0', 'ADX', 'AO1',
                                                      'CI0', 'DO1', 'DP9', 'O20',
                                                      'PWO', 'TO1', 'WO1', 'WO2' ) 
                    THEN (Cost_Values)
                      ELSE NULL
                    END),

   item_no,
   comp_item_no
FROM     table_1

GROUP BY item_no,
     comp_item


来源:https://stackoverflow.com/questions/37865838/sql-summing-case-when-values-from-different-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!