我有一个只是随机值的表。 我的查询看起来像这样:
SELECT COUNT(DISTINCT(Value))
FROM RandomValueTable
WHERE
Value > @lowerRange
AND
Value < @upperRange
我需要运行一系列范围(0-20,21-45,46-100等)。在运行此查询之前,我将知道范围是什么。我是否需要多次运行此查询才能填写范围变量,或者是否可以通过某种方式在一个查询中指定所有不同的范围?
答案 0 :(得分: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);