Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use common table expressions [CTE's], indicated by <code>WITH</code>, to break the logic down into logical steps. First we'll build the summary rows, then we'll assign a ranking to the rows within each group, then pick out the ones that with the highest count of records.</p> <p>Let's say we want to know which flavor of each item sells the most frequently on each date (perhaps assuming a record is quantity one). </p> <pre><code>WITH s as ( SELECT itemID, saleDate, flavor, count(*) as tally FROM sales GROUP BY itemID, saleDate, flavor ), r as ( SELECT itemID, saleDate, flavor, tally, RANK() OVER (PARTITION BY itemID, saleDate ORDER BY tally desc) as pri FROM s ) SELECT itemID, saleDate, flavor, tally FROM r WHERE pri = 1 </code></pre> <p>Here the names "s" and "r" refer to the result set from their respective CTE's. These names can then be used as to represent a table in another part of the statement.</p> <p>The pri column will have the RANK() of tally value on the summary row from the first section "s" within the window of itemID and saleDate. Tally is descending, because we want the largest value first, which will get a RANK() of 1. Then in the main SELECT we simply pick those summary records which were first in their partition.</p> <p>By using RANK() or DENSE_RANK() we could get back multiple flavors for an itemID, saleDate, if they are tied for first place. This could be eliminated by replacing RANK() with ROW_NUMBER(), but it would arbitrarily pick one of the tied flavors as a winner, and this may not be correct answer for the problem at hand.</p> <p>If we had a sales quantity column in the table, we could replace COUNT(*) with SUM(salesqty) and find what had sold the most units.</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.
 

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