Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to order sql server query with one to many relationship and pagination
    primarykey
    data
    text
    <p>I have an sql server database full of products and each product has 1 style record and 1 or more sku records. I'm able to successfully paginate my queries on these tables using dense_rank(), but I can't for the life of me figure out how to order the styles based on a column other than the style_id and still be able to add a an incremental rank to each style.</p> <p>I'm currently using this query:</p> <pre><code>SELECT * FROM ( SELECT styles.style_id styles.department, styles.style, styles.brand, styles.description, skus.sku_id, skus.color, skus.size, skus.price, skus.creation_date, DENSE_RANK() OVER (ORDER BY styles.style_id) AS style_rank FROM skus LEFT OUTER JOIN styles ON styles.style_id=skus.style_id WHERE skus.color='blue' AND styles.brand='acme' ) AS t1 WHERE t1.style_rank &gt; 0 AND t1.style_rank &lt;= 25 </code></pre> <p>The above will allow me to paginate at the style level, but I need to be able to sort these styles based on price ASC/DESC or creation_date ASC/DESC. It would be nice to be able to control the sorting with an aggregate function like sort styles by MAX(skus.price), but that is not necessary. </p> <p>To clarify, one style may have three skus and each of these three skus could be a different price.</p> <p>This seems to be a pretty basic need for any retail website using RDBMS, but I cant find any documentation on how to do this.</p> <p>Any suggestions on how this could be done would be much appreciated. </p> <p>EDIT: I solved this using two queries (shown in my answer below). </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload