tsql - SQL Query to calculate first n customers based on quantity conditions -
i have question not sure how ask.
here example.
product customer txdate qty apple peter 2013/02/02 3 apple edward 2013/02/03 5 apple sally 2013/02/06 3 apple emily 2013/02/08 6 orange ray 2013/02/03 5 orange simon 2013/02/04 4 orange billy 2013/02/05 5 orange david 2013/02/06 2
i want know have purchased first 10 (variable in each product) items , wish query return following results:
apple peter 2013/02/02 3 apple edward 2013/02/03 5 apple sally 2013/02/06 2 orange ray 2013/02/03 5 orange simon 2013/02/04 4 orange billy 2013/02/05 1
i not familiar t-sql therefore appreciated.
thanks lot.
use option apply operator , correlated-subquery
;with cte ( select product, customer, txdate, isnull(newqty, 10 - max(totalqty) over(partition product)) qty, max(total) over(partition product) ismatch dbo.test117 t cross apply( select case when sum(t2.qty) > 10 null else t.qty end, case when sum(t2.qty) > 10 null else sum(t2.qty) end, sum(t2.qty) dbo.test117 t2 --with(forceseek) t.product = t2.product , t.txdate >= t2.txdate having sum(t2.qty) - t.qty < 10 ) o(newqty, totalqty, total) ) select product, customer, txdate, qty cte ismatch >= 10
demo on sqlfiddle
in order improve performance use index:
create index x on dbo.test117(product) include(customer, txdate, qty)
Comments
Post a Comment