Skip to content
Advertisement

SQL for storing numbers from cold to hot for specific range?

We have a table that looks list this: date, val1, val2, val3, val4, val5

for a given row, val1 -val5 are unique and between 1 and 37

Using T-SQL, How can I list numbers 1 -37 by cold to hot with their frequency for a given date range?

[![enter image description here][1]][1]

Sample Output (NOT ACTUAL): Numbers by frequency descending:

36=0, 2=1, 5=1, 7=3, 34=5, 30=6, etc.

Advertisement

Answer

With a recursive CTE create the dataset 1-37 and then UNION ALL to create a dataset with all the numbers in the table.
Join the 2 datasets and group by the number and aggregate:

with cte(n) as (
  select 1 union all select (cte.n + 1) n from cte where cte.n < 37
) 

select 
  cte.n, count(t.number) counter
from cte left join (
  select date, val1 number from tablename union all
  select date, val2 from tablename union all
  select date, val3 from tablename union all
  select date, val4 from tablename union all
  select date, val5 from tablename
) t on t.number = cte.n and t.date between '2019-05-01' and '2019-05-31'
group by cte.n
order by counter, cte.n
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement