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

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.
  • 2
1 Solution
Pawan KumarDatabase ExpertCommented:
can you explain more.. not clear when to take the SUM sales amount .
Éric MoreauSenior .Net ConsultantCommented:
Would it be:

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

Open in new window

Pawan KumarDatabase 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
	SELECT SUM(saleamount) saleamount1
	FROM SumQuantity s 
	WHERE s.Quantity = r.st

Open in new window

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)

Open in new window

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.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now