tsql - "Partitioned" sorting in a SQL query -


the following sql query displays products sold sorted cost , number of orders have sorted in partitioned manner. namely, products cost of under $100 should go first , else > $100 should follow it. adding having ts.totalsold < 100 query accomplish first partition, filter out other products. operation should atomic, query can executed once.

note: cost query has partitioned calculated max of 2 cost columns, makes things bit more complicated (the proposed solutions of case when won't work highestcost not column)

 select ps.productname, ts.totalsold,    ((ps.cost1 + ps.cost2 + abs(ps.cost1-ps.cost2)) / 2) highestcost products ps    cross apply        (select           (select count(orderid)            orders os            os.productid=ps.productid)         totalsold) ts order highestcost asc, ts.totalsold 

edit: modified query include calculated cost query has partitioned.

edited

select * ( select ps.productname, ts.totalsold,    ((ps.cost1 + ps.cost2 + abs(ps.cost1-ps.cost2)) / 2) highestcost products ps    cross apply        (select count(orderid) totalsold        orders os         os.productid=ps.productid) ts ) sq order case when highestcost > 100 1 end asc, totalsold 

original below

select ps.productname, ts.totalsold products ps    cross apply        (select count(orderid) totalsold        orders os         os.productid=ps.productid) ts order  case when ts.totalsold > 100 1 end, ps.cost asc, ts.totalsold 

you may notice removed subquery level since extraneous.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -