在 T-SQL 上计算项目频率时出现问题
我正在尝试计算表中不同字段中从 1 到 100 的数字出现的频率。
假设我有包含以下数据的“结果”表:
LottoId Winner Second Third
--------- --------- --------- ---------
1 1 2 3
2 1 2 3
我希望能够获得每个数字的频率。为此,我使用以下代码:
--Creating numbers temp table
CREATE TABLE #Numbers(
Number int)
--Inserting the numbers into the temp table
declare @counter int
set @counter = 0
while @counter < 100
begin
set @counter = @counter + 1
INSERT INTO #Numbers(Number) VALUES(@counter)
end
--
SELECT #Numbers.Number, Count(Results.Winner) as Winner,Count(Results.Second) as Second, Count(Results.Third) as Third FROM #Numbers
LEFT JOIN Results ON
#Numbers.Number = Results.Winner OR #Numbers.Number = Results.Second OR #Numbers.Number = Results.Third
GROUP BY #Numbers.Number
问题是计数对每个数字重复相同的值。在这种特殊情况下,我得到以下结果:
Number Winner Second Third
--------- --------- --------- ---------
1 2 2 2
2 2 2 2
3 2 2 2
...
当我应该得到这个结果时:
Number Winner Second Third
--------- --------- --------- ---------
1 2 0 0
2 0 2 0
3 0 0 2
...
我错过了什么?
I'm trying to count the frequency of numbers from 1 to 100 on different fields of a table.
Let's say I have the table "Results" with the following data:
LottoId Winner Second Third
--------- --------- --------- ---------
1 1 2 3
2 1 2 3
I'd like to be able to get the frequency per numbers. For that I'm using the following code:
--Creating numbers temp table
CREATE TABLE #Numbers(
Number int)
--Inserting the numbers into the temp table
declare @counter int
set @counter = 0
while @counter < 100
begin
set @counter = @counter + 1
INSERT INTO #Numbers(Number) VALUES(@counter)
end
--
SELECT #Numbers.Number, Count(Results.Winner) as Winner,Count(Results.Second) as Second, Count(Results.Third) as Third FROM #Numbers
LEFT JOIN Results ON
#Numbers.Number = Results.Winner OR #Numbers.Number = Results.Second OR #Numbers.Number = Results.Third
GROUP BY #Numbers.Number
The problem is that the counts are repeating the same values for each number. In this particular case I'm getting the following result:
Number Winner Second Third
--------- --------- --------- ---------
1 2 2 2
2 2 2 2
3 2 2 2
...
When I should get this:
Number Winner Second Third
--------- --------- --------- ---------
1 2 0 0
2 0 2 0
3 0 0 2
...
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 SQL Server 2005+
另一种可能的解决方案适用于旧版本的 SQL Server:
If you are using SQL Server 2005+
Another possible solution which will work in older versions of SQL Server:
您可以使用 PIVOT 和 UNPIVOT。
You can use PIVOT and UNPIVOT.