0

我有一个只是随机值的表。我有一个看起来像这样的查询:

SELECT COUNT(DISTINCT(Value))
FROM RandomValueTable
WHERE
    Value > @lowerRange
AND
    Value < @upperRange

我需要运行一系列范围(0-20、21-45、46-100 等)。在运行这个查询之前,我会知道范围是什么。我是否需要多次运行此查询,只需填写范围变量,还是有什么方法可以在一个查询中指定所有不同的范围?

4

1 回答 1

1

您可以使用以下方式在一个查询中指定它们group by

select (case when value between 0 and 20 then '0-20'
             when value between 21 and 45 then '21-45'
             when value between 46 and 100 then '46-100'
             else 'other'
        end) as range,
       count(*)
from RandomValueTable
group by (case when value between 0 and 20 then '0-20'
               when value between 21 and 45 then '21-45'
               when value between 46 and 100 then '46-100'
               else 'other'
          end);
于 2013-09-17T14:28:07.513 回答