计算列sql的每个值的百分比

时间:2013-01-03 13:24:56

标签: sql

我想重写这个sql查询,以便在没有匹配的情况下显示相应年龄范围为0的记录,我希望他计算会员的每个值而不是'0'的百分比,任何人都可以帮助我如何实现这一目标吗?

SELECT COUNT(Name) * 100 / 
    (select COUNT(*) from 'cities'
    WHERE city= 'Hoeselt' AND Member = '0' ) AS 'perc', 
    CASE 
        WHEN age <= 30 THEN '18-30'
        WHEN age <= 50 THEN '31-50'
        ELSE '50+'
    END AS age, COUNT(*) AS n 
FROM 'cities' 
    WHERE city= 'Hoeselt' AND elected='yes' AND Member= '0'
    GROUP BY CASE
        WHEN age <= 30 THEN '18-30'
        WHEN age <= 50 THEN '31-50'
        ELSE '50+'
    END

2 个答案:

答案 0 :(得分:0)

如果没有DDL,很难确定这对您有用。 这是帮助人们为您提供最佳解决方案的绝佳工具。 http://sqlfiddle.com/#!6

;WITH AgeCat AS
(
    SELECT   MinAge = 18
            ,MaxAge = 30
            ,Descr  = '18-30'   UNION ALL
    SELECT 31, 49, '31-49'      UNION ALL
    SELECT 50, 200, '50+'
)
SELECT   DISTINCT
         C.Descr
        ,Perc   = COUNT(*) OVER (PARTITION BY 0) / COUNT(*) OVER (PARTITION BY A.Descr) * 100
FROM AgeCat A
JOIN Cities C   ON C.Age BETWEEN A.MinAge AND A.MaxAge
WHERE city = 'Hoeselt'
AND elected = 'yes'
AND Member = '0'

答案 1 :(得分:0)

我的方法是使用CTE来定义年龄组。接下来选择所有年龄组作为“驱动程序”表,左边加入城市信息。然后,即使没有匹配项,您也有年龄组:

with c as (
    select c.*,
           (CASE WHEN age <= 30 THEN '18-30'
                 WHEN age <= 50 THEN '31-50'
                 ELSE '50+'
             END) as agegrp
    from cities
   )
select COUNT(Name) * 100 / (select COUNT(*) from cities WHERE city= 'Hoeselt' AND Member = '0') as perc,
       driver.agegrp,
       COUNT(*) as n
from (select distinct agegrp from c) as driver left outer join
     c
     on driver.agegrp = c.agegrp
group by driver.agegrp