Search code examples
sqlsql-servert-sqlcountunpivot

T-SQL: calculate number of occurrences across columns and rows


I have a table like this:

nr1 nr2 nr3 nr4 nr5 nr6 nr7 nr8 nr9 nr10
----------------------------------------
1   4   5   6   8   9   10  17  18  19
3   4   5   7   10  11  14  15  17  18
1   3   5   9   10  12  13  15  16  18
2   3   4   7   8   11  15  16  17  19
5   6   8   9   10  11  13  14  16  19
2   4   8   10  11  12  13  14  19  20
2   5   7   8   10  14  15  16  18  19
1   5   7   8   9   12  13  14  15  18
1   2   3   4   7   10  11  12  14  17
1   3   5   6   7   10  13  14  17  20

I would like to achieve the following:

  1. Put all those numbers in a #TEMP table containing just one column
  2. Count the number of occurrences of all numbers

The second I believe I can achieve easily once 1 have all numbers in just one column. But I'm stuck on first item. How to put all those values just in 1 column.

I tried UNPIVOTing but it doesn't work because I do something wrong.

SELECT nr1, nr2, nr3, nr4, nr5, nr6, nr7, nr8, nr9, nr10
FROM table t
UNPIVOT
(
Number for nrs in ( nr1, nr2, nr3, nr4, nr5, nr6, nr7, nr8, nr9, nr10)
) AS u

Solution

  • You don't need a temp table for this. You can just use cross apply and values():

    select x.nr, count(*) cnt
    from mytable t
    cross apply (values (nr1), (nr2), (nr3), ..., (nr10)) x(nr)
    group by x.nr