我需要根据不同的标准在同一个查询中得到两个求和。两个标准都在同一列上运行。 有没有办法做到这一点?
我最好用一个例子解释一下:
表: salary_survey_result
柱: 行业, 地点, 位置, 薪水
实际上我想要结合以下两个查询:
SELECT industry, location, count(*) as MORE_THAN_SIX_FIGURE
FROM salary_survey_result
WHERE salary > 100000
GROUP BY industry, location
和
SELECT industry, location, count(*) as MORE_THAN_FIVE_FIGURE
FROM salary_survey_result
WHERE salary > 10000
GROUP BY industry, location
所以结果是这样的:
industry location MORE_THAN_FIVE_FIGURE MORE_THAN_SIX_FIGURE
Healthcare NY 45 10
Healthcare MN 35 6
InfoTech NY 50 19
InfoTech MN 40 12
答案 0 :(得分:8)
像
这样的东西SELECT industry,
location,
sum( case when salary >= 10000 then 1 else 0 end) as MORE_THAN_FIVE_FIGURE,
sum( case when salary >= 100000 then 1 else 0 end) as MORE_THAN_SIX_FIGURE
FROM salary_survey_result
WHERE salary >= 10000
GROUP BY industry, location
结果不需要WHERE salary >= 10000
子句。如果SALARY
上有索引并且大多数工资值小于10000,它可能会提高性能。请注意,我还假设你的意思是>=
而不是>
,因为工资是10,000是五位数的薪水。
答案 1 :(得分:-2)
SELECT industry, location, count(*) as MORE_THAN_FIVE_FIGURE ,sum(salary > 100000) as MORE_THAN_SIX_FIGURE
FROM salary_survey_result
WHERE salary > 10000
GROUP BY industry, location