第1或第0小组的汇总

时间:2015-06-11 23:20:59

标签: sql sql-server group-by case

我试图通过从一个表创建子组来聚合数据,指标是1或0.我可以想象我们如何创建指标met = 1和指标met = 0的子组,我可以UNION他们为我要求的输出。有关如何编写单个查询以实现此目的的任何查询想法?而不是UNIONING两个查询结果。

3 个答案:

答案 0 :(得分:0)

尝试按案例陈述分组:

Select 'Chicago' as region
  , district
  , school
  , case indicator when 0 then 'NOT MET' when 1 then 'MET' end as Indicator
  , count(distinct ID) as total
[etc.]
from Table
where year = 2013
and indicator in (1,0) --optional, if these are the only possible values
group by 
    district
    , school
    , case indicator when 0 then 'NOT MET' when 1 then 'MET' end 

可能还想考虑将with rollup添加到group by

答案 1 :(得分:0)

如何将指标添加到分组集中?

SELECT 'Chicago' AS Region, District, SchoolName AS School,
       (CASE WHEN indicator = 1 THEN 'Indicator Met' ELSE 'Indicator Not Met'
        END) AS Type,
       COUNT(DISTINCT id) AS Total, SUM(Flag) AS Met
FROM final.table
WHERE Year = 2013
GROUP BY GROUPING SETS(( district, indicator ),
                       ( district, Schoolname, indicator ), (indicator));

答案 2 :(得分:0)

也许是您的指标分组的子查询。

SELECT
 *
FROM
(
    SELECT  'Chicago' AS Region ,
               District ,
                SchoolName AS School,
                'Indicator Met' AS Type,
            COUNT(DISTINCT id) AS Total ,
            SUM(Flag) AS Met,
            Indicator
    FROM    final.table
    WHERE   Year = 2013
    GROUP BY Indicator,District,SchoolName  
)AS X
WHERE
    Indicator IN(0,1)
GROUP BY GROUPING SETS(( district ),
                       ( district, Schoolname ), ( ))