我想对表中符合条件colA <= x < colB
的条目的数量进行分组和计数
假设我有下表:
index Game MinAgeInclusive MaxAgeExclusive -------------------------------------------------------- 1 Candy Land 3 8 2 Checkers 5 255 3 Chess 12 255 4 Sorry! 6 12 5 Monopoly 10 30
(this isn't what I'm doing, but it abstracts away a lot of the other complications with my setup)
Suppose I wanted to get a table that told me how many games were appropriate for different ages:
Age NumberOfAgeAppropriateGames ---------------------------------- 0 0 ... 3 1 4 1 5 2 6 3 7 3 8 2 9 2 10 3 ... 40 2
I can certainly get the value for a single age:
SELECT
COUNT(*)
FROM GameTable
WHERE MinAgeInclusive <= age AND age < MaxAgeExclusive
而且我知道如何获取具有给定
MaxAgeExclusive
的项目的数量SELECT
MaxAgeExclusive, COUNT(*) AS GameCount
FROM GameTable
GROUP BY MaxAgeExclusive
但是我不知道该怎么做。
由于我的实际应用程序是在具有数百万个条目的表上执行此操作的,并且可能必须确定
x
的数千个值的计数,因此我希望可以通过在单个查询中完成全部操作来最大化性能。 最佳答案
要以合理的通用方式执行此操作,最好为它创建一个辅助数字表,该表具有从0到最大值的数字序列,然后使用类似以下的内容。
SELECT
COUNT(*) AS GameCount, N.Number
FROM Numbers N
LEFT OUTER JOIN GameTable ON
MinAgeInclusive <= N.Number AND N.Number < MaxAgeExclusive
WHERE N.Number < 100
GROUP BY N.Number
关于sql - 如何使用SQL分组和计算行数,其中一列的值为<= x,另一列的值为> x?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3236768/