为什么这个投票/职位比率总是1?

时间:2015-07-13 13:42:21

标签: sql sql-server tsql dataexplorer

我正在与SEDE合作创建投票与职位比率的图表。消除了所有实际错误后,我遇到了一个新问题:由于某种原因,比率总是 1.这是当前的SQL:

SELECT CAST(p.CreationDate AS DATE) AS [CreationDate],
       COUNT(CAST(v.CreationDate AS DATE)) / COUNT(CAST(p.CreationDate AS DATE))
         AS [Ratio]
FROM Posts p
INNER JOIN Votes v ON v.PostId = p.Id
WHERE v.VoteTypeId = ##VoteType:int?2## AND
      p.PostTypeId = 1 OR p.PostTypeId = 2
GROUP BY CAST(p.CreationDate AS DATE)
ORDER BY Ratio

查询本身可以找到here

这可能是suggested in chat,因为加入表会产生所有可能的组合,因此投票数和帖子总数相同(因此n/n = 1)。这是正确的,如果是的话,我应该做什么呢?

1 个答案:

答案 0 :(得分:2)

由于内连接的两侧都存在,COUNT(CAST(v.CreationDate AS DATE))COUNT(CAST(p.CreationDate AS DATE))都将返回完全相同的数字,即组中的行数 *

如果您想计算在指定日期每个新帖子的新票数,请使用COUNT(DISTINCT)

SELECT CAST(p.CreationDate AS DATE) AS [CreationDate],
       COUNT(DISTINCT v.Id) / COUNT(DISTINCT p.Id) AS [Ratio]
FROM Posts p
INNER JOIN Votes v ON v.PostId = p.Id
WHERE v.VoteTypeId = ##VoteType:int?2## AND
      p.PostTypeId = 1 OR p.PostTypeId = 2
GROUP BY CAST(p.CreationDate AS DATE)
ORDER BY Ratio

* 假设CreationDate不可为空。