在比较同一列中的数据时,我需要帮助。例如我有一个包含ID,名称,地址,城市,州和星星列的业务表。
“星星”列包含以下值:1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5、5.0。
现在我必须将2-3星的企业与4-5星的企业进行比较,那么我该怎么做?任何帮助表示赞赏。
谢谢。
答案 0 :(得分:1)
我猜“他们”想要每颗恒星数。
如果是这样,那么您可以在一个CASE上分组。
SELECT
(CASE
WHEN stars BETWEEN 0.0 AND 1.5 THEN '0.0-1.5'
WHEN stars BETWEEN 2.0 AND 3.5 THEN '2.0-3.5'
WHEN stars BETWEEN 4.0 AND 5.0 THEN '4.0-5.0'
END) as stars_range,
COUNT(*) AS TotalBusiness,
COUNT(DISTINCT city) AS TotalCities,
COUNT(DISTINCT state) AS TotalStates
FROM Business
WHERE stars BETWEEN 2.0 AND 5.0
GROUP BY
(CASE
WHEN stars BETWEEN 0.0 AND 1.5 THEN '0.0-1.5'
WHEN stars BETWEEN 2.0 AND 3.5 THEN '2.0-3.5'
WHEN stars BETWEEN 4.0 AND 5.0 THEN '4.0-5.0'
END)
还是有条件的聚合看起来更好?
SELECT
COUNT(CASE WHEN stars BETWEEN 2.0 AND 3.5 THEN 1 END) AS stars_2_3,
COUNT(CASE WHEN stars BETWEEN 4.0 AND 5.0 THEN 1 END) AS stars_4_5
FROM Business
WHERE stars BETWEEN 2.0 AND 5.0