Skip to content
Advertisement

How to optimize my query speed (avoid using subselect for every row)?

I have a table called CisLinkLoadedData. Is has Distributor, Network, Product, DocumentDate, Weight, AmountCP and Quantity columns. It used to store some product daily sales. AmountCP / Quantity is the price for the product at certain date. There are promo and regular sales, but no flag for it. We can tell if certain record is regular or promo by comparing it’s price with the maximum recorded price within month. I did explained it on this picture. enter image description here

I need to make a query to display summarized regular and promo sales of certain product per month. Well, I made it, but it very slow (6 minutes to execute at 1.6 millions records). I suspect this is because I use subquery to determine max price for every record, but I don’t know how to make it another way.

This is what I made:

What is possible to do in such case? By the way, if you can do result table with another structure like that (Distributor, Network, Product, MonthYear, RegularWeight, PromoWeight) – it’s even better. This is what I tried initially, but failed. I use Microsoft SQL Server.

Advertisement

Answer

Rather than a correlated subquery, you could use a windowed function to retrieve the maximum price per group (each group is defined by the partition by clause):

I think your full query would end up something like:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement