SQL- Summing Case/When values from different field

2019-09-12 07:52发布

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

Example:
enter image description here
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条回答
家丑人穷心不美
2楼-- · 2019-09-12 07:52

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
查看更多
登录 后发表回答