我正在寻找我认为是一项简单任务的帮助。 :(
我在SQL Server实例中有一个包含以下列和数据的表:
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
答案 0 :(得分:4)
对所需结果和SQL Server版本做出一些假设
SELECT Number,
COUNT(*) AS [Count]
FROM YourTable
CROSS APPLY (VALUES(num1),(num2),(num3),(num4),(num5)) V(Number)
GROUP BY Number
答案 1 :(得分:3)
您可以使用UNPIVOT语句将所有值放入一列。然后是一个简单的GROUP BY和COUNT
select value, count(*)
from nums
unpivot
(
value
for col in (num1, num2, num3, num4, num5)
) u
group by value
答案 2 :(得分:0)
上述评论示例:
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