• Status: Solved
• Priority: High
• Security: Public
• Views: 66

# sql value based on a couple variables

quantity      product      desction          type          saleamount
315              xyz        product1                                      100
315             mnd        product2                                         200
315        dnd        product3                                          563
14             dioa        product4                                       456
315             xxx         product5              J                       144
1             ddd        product6                                        226
315             dqi         product7                                         144

So i'm trying to sum the saleamount product based on the following

take the quantity of the row where type is 'J' (So this would be 315) then SUM sales amount column if quantity has 315.  so the value would be 1151
this would be dynamic since this is just an example.
0
Southern_Gentleman
• 2
1 Solution

Database ExpertCommented:
can you explain more.. not clear when to take the SUM sales amount .
0

Senior .Net ConsultantCommented:
Would it be:

select sum(saleamount)
from TableName
where quantity = (select top 1 Quantity from TableName where type = 'J')
0

Database ExpertCommented:
Please try this ..tested and dynamic solution ..
This should work for larger data. Please let us know in case of any changes required.

SELECT r.Quantity,r.product,r.desction,r.type,CASE WHEN r.type = 'j' THEN g.saleamount1 ELSE r.saleamount END saleamount FROM
(
SELECT * , CASE WHEN [type] = 'J' THEN Quantity END st
FROM SumQuantity
)r
CROSS APPLY
(
SELECT SUM(saleamount) saleamount1
FROM SumQuantity s
WHERE s.Quantity = r.st
)g

OUTPUT
/*------------------------
OUTPUT
------------------------*/
Quantity    product desction        type saleamount
----------- ------- --------------- ---- -----------
315         xyz     product1        NULL 100
315         mnd     product2        NULL 200
315         dnd     product3        NULL 563
14          dioa    product4        NULL 456
315         xxx     product5        J    1151
1           ddd     product6        NULL 226
315         dqi     product7        NULL 144

(7 row(s) affected)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.