SQL服务器:跨列计数

SQL Server: Count number across columns

我正在寻求帮助以完成我认为很简单的任务。 :(

我在 SQL 服务器实例中有一个 table,它包含以下列和数据:

num1   num2   num3   num4   num5
1      34     15     22     45
23     4      2      100    23
1      23     23     100    5

我想得到计算所有数字出现次数的结果:

Number  Count
1       2
2       2
3       0
4       1
5       1
6       0

对预期结果和您的 SQL 服务器版本做出一些假设

SELECT Number,
       COUNT(*) AS [Count]
FROM   YourTable
CROSS APPLY (VALUES(num1),(num2),(num3),(num4),(num5)) V(Number)
GROUP BY Number

我上面的评论示例:

SELECT Number, COUNT(*) AS Count FROM (
SELECT num1 AS Number FROM MyTable
UNION ALL 
SELECT num2 AS Number FROM MyTable
UNION ALL 
SELECT num3 AS Number FROM MyTable
UNION ALL 
SELECT num4 AS Number FROM MyTable
UNION ALL 
SELECT num5 AS Number FROM MyTable
) t
GROUP BY Number

您可以使用 UNPIVOT 语句将所有值放入一列中。然后是一个简单的 GROUP BY 和 COUNT

select value, count(*)
from nums
unpivot
(
  value
  for col in (num1, num2, num3, num4, num5)
) u
group by value

SQL Fiddle