Home > other >  Summing up values of Some rows and add it to Value of other rows
Summing up values of Some rows and add it to Value of other rows

Time:11-26

I need your help in SQL Query where in the example table given below, i just need two rows which doesn't have a Required flag set to Y. Value of these two rows should have (Price * % Levied) (sum of (Price)*(% Levied) of rows which has Required flag set to Y)

Name Price % Levied Required
King Bed 10000 120
Queen Bed 24000 140
Delivery 240 140 Y
Porter Charges 20 20 Y

My result should look something like this

Name Values
King Bed (10000 * 120) (240 * 140) (20 * 20)
Queen Bed (24000 * 140) (240 * 140) (20 * 20)

I don't even know where to get started. Let me know if any info is needed. Thanks in advance.

CodePudding user response:

SELECT t1.Name, t1.Price * t1.Levied   t3.CommonPayment Values
FROM table t1
CROSS JOIN ( SELECT SUM(t2.Price * t2.Levied) CommonPayment
             FROM table t2 
             WHERE t2.Required = 'Y' ) t3 
WHERE t1.Required <> 'Y'

CodePudding user response:

Try something like this

with required_rows as
(
    select  Price * '% Levied' as 'add_on_price'
    from    my_table
    where   Required = 'Y'
),
sum_required_rows as
(
    select sum (add_on_price) as total_add_on_price
    from   required_rows 
),
select  Name,
        Price,
        % Levied,
        ((Price * '% Levied')   total_add_on_price) as final_price
from    my_table
inner join sum_required_rows on 1=1
where   Required != 'Y'   
  • Related