tsql - What to do with same subquery repeating many times in select statement, if it includes outside condition -



tsql - What to do with same subquery repeating many times in select statement, if it includes outside condition -

i'll seek create specific possible. have table containing transaction info on items. possible transactions purchase (type_id: 1) , sale(type_id: 2). stripped downwards version of table "transactions" following:

transaction_id item_id transaction_type_id quantity cost date

1, 1, 1, 50, 10, 6/1,

2, 2, 1, 40, 20, 13/1,

3, 1, 2, 10, 13, 14/1,

4, 2, 2, 20, 25, 3/2,

5, 1, 2, 20, 12, 20/2

i have next query:

select b.item_id b.quantity - (select sum(quantity) transactions a.item_id = b.item_id , a.transaction_type_id = 2) 'quantity left' b.price * (b.quantity - (select sum(quantity) transactions a.item_id = b.item_id , a.transaction_type_id = 2)) 'purchase amount left' transaction b b.transaction_type_id = 1 , b.quantity - (select sum(quantity) transactions a.item_id = b.item_id , a.transaction_type_id = 2) > 0

like may noticed, trying purchased items still in stock. may notice there annoying sub-query repeating twice in select clause , 1 time in clause. how can cut down it? possible utilize in origin of statement in case?

thank you!!

join onto aggregated derived table?

select b.item_id b.quantity - isnull(a.sumquantity, 0) 'quantity left', b.price * (b.quantity - isnull(a.sumquantity, 0)) 'purchase amount left' transaction b left bring together ( select sum(quantity) sumquantity, item_id transaction transaction_type_id = 2 grouping item_id ) on a.item_id = b.item_id b.transaction_type_id = 1 , b.quantity - isnull(a.sumquantity, 0) > 0

if have rows transaction_type_id = 2, can remove left bring together , isnull. in current code, assume have rows.

it looks you're mixing entities in same table based on transaction_type_id. simple sum(quantity) .. grouping item_id more right if - sales <0 quantity transaction - restocks >0 quantity transaction2

tsql sql-server-2008-r2

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -