Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It seems to me that the question calls for a query that would return best, and second best in the same row for each month and year, like so:</p> <pre><code>month, year, best, second best ... ... </code></pre> <p>and not two rows for the same month and year containing best and second best value.</p> <p>This is the solution that I came up with, so if anyone has a simpler way of achieving this, I would like to know.</p> <pre><code>with ranks as ( select year(entrydate) as [year], month(entrydate) as [month], views, rank() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank] from product ) select t1.year, t1.month, t1.views as [best], t2.views as [second best] from ranks t1 inner join ranks t2 on t1.year = t2.year and t1.month = t2.month and t1.rank = 1 and t2.rank = 2 </code></pre> <p>EDIT: Just out of curiosity I did a bit more testing and ended up with a simpler variation on the <a href="https://stackoverflow.com/questions/4440598/query-to-find-the-first-and-second-largest-value-from-a-group/4443936#4443936">Stephanie Page's answer</a> that doesn't use an aditional subquery. And I changed the rank() function to row_number() as it doesn't work when two max values are the same.</p> <pre><code>with ranks as ( select year(entrydate) as [year], month(entrydate) as [month], views, row_number() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank] from product ) select t1.year, t1.month, max(case when t1.rank = 1 then t1.views else 0 end) as [best], max(case when t1.rank = 2 then t1.views else 0 end) as [second best] from ranks t1 where t1.rank in (1,2) group by t1.year, t1.month </code></pre>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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