简体   繁体   中英

SQL - Summing values from different rows using Case, When

I am trying to find Labor and Overhead for items for a report. Labor and Overhead are found by manipulating data found in a Factor column and a Rate column. These factors and rates are classified by different Types. It is much more complex than it needs to be, and it is my job to make sense of it.

Here is a snippet of data returned with the Cost Column unsorted. 在此处输入图片说明

When the Type = W10, then the costs are Labor based, when the Type = WO1 or WO2, then the costs are Overhead based.
My predicament falls to the fact that I have to add the values found when Type = 'WO1, WO2' together to get total Overhead costs.
I decided to go use CASE/WHEN to try to get the data I need, but I cannot figure out how to add the cost for Overhead together.

My code so far is:

SELECT DISTINCT 'LABOR' = CASE 
WHEN TYPE = 'W10' THEN (FACTOR * RATE)
ELSE 0 
END, //This part is fine//
'OVERHEAD' = CASE 
WHEN TYPE = 'WO1, WO2' THEN SUM(FACTOR * RATE) 
ELSE 0
END,

FROM TABLE_1  

However, the SUM(Factor * Rate) is not summing the two rows of Costs when Type = WO1 or WO2, it is returning 0 like this:

在此处输入图片说明

I don't know how well I described my problem, but it would be so great if you guys could help figure this problem out.

Try with

when type IN ('W01','W02')

Writing TYPE = 'WO1, WO2' you're looking for 'W01,W02' and not one of them.

Because the statement above doesn't work fine, according to the applicant, I add this one:

'OVERHEAD' = CASE 
WHEN TYPE = 'WO1' THEN SUM(FACTOR * RATE) 
WHEN TYPE = 'WO2' THEN SUM(FACTOR * RATE) 
ELSE 0
END,

Lets create some sample data and try

CREATE TABLE TABLE_1 (rate FLOAT, Factor FLOAT, costs FLOAT, Type VARCHAR(3))

INSERT INTO TABLE_1
VALUES (.225000, 33.00000, 7.4250000, 'W10')

INSERT INTO TABLE_1
VALUES (1.0000, 14.8500, 14.8500, 'W01')

INSERT INTO TABLE_1
VALUES (1.0000, 1.1666, 1.16660000, 'W02')

I hope I have only added the first item A If I understand the problem the issue resides in the GROUP BY clause. If I re - write the code as below and grouped the W01 and W02 together before calculation you will get the desired result.

SELECT CASE 
        WHEN [TYPE] = 'A'
            THEN SUM(N)
        ELSE 0
        END AS labour
    ,CASE 
        WHEN [TYPE] IN ('B')
            THEN SUM(N)
        ELSE 0
        END AS overhead
FROM (
    SELECT rate * factor AS n
        ,CASE 
            WHEN type = 'W10'
                THEN 'A'
            WHEN type IN ('W01', 'W02')
                THEN 'B'
            ELSE ''
            END AS type
    FROM table_1
    ) AS t
GROUP BY [type] 

I hope this is the result you wanted if not please post the DDL and some sample data with required output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM