繁体   English   中英

使用 Case 语句计算分组计数

[英]Calculating Grouped Counts while using Case Statement

使用 SQL Server 2012 - 我正在尝试从数据库中完成对不同实体的计数,这些实体按国家和地区以及公司类型进行分组。 后一部分是问题所在——因为有这么多“类型”,我试图将它们分为 3 类:公共的、私有的,并且使用 case 语句将所有其他内容都归入“其他”。

查询生成我想要的 output 但是我无法获得将计数分组到我选择的类别中的查询。 我最初在 select 主查询中有 CASE 语句,但在其他地方发现类似问题后,我将其移至子查询,但我遇到了同样的问题。 使用示例 output 在下方查询:

SELECT COUNT(DISTINCT ent.factset_entity_id) AS Count, 
    d.[Entity Type], 
    YEAR(r.repr_timeslot_date) AS [Year], 
    cty.country_desc AS Country, 
    reg.region_desc AS Region
FROM
    (SELECT 
         entity_type_code,
         CASE
            WHEN entity_type_code = 'PUB'
               THEN 'Public'
            WHEN entity_type_code IN ('PVT', 'HOL', 'JVT', 'SUB')
               THEN 'Private'
            ELSE 'Other'
         END AS [Entity Type]
     FROM   
         ref_v2.entity_type_map) AS d
JOIN 
    sym_v1.sym_entity AS ent ON ent.entity_type = d.entity_type_code
JOIN 
    sdfdemo.sym_v1.sym_sec_entity AS se ON ent.factset_entity_id = se.factset_entity_id
JOIN 
    repr_v1.repr_factset_id_map AS reprisk ON se.fsym_id = reprisk.factset_id
JOIN 
    repr_v1.repr_rri AS r ON r.repr_company_id = reprisk.provider_id
JOIN 
    ref_v2.country_map AS cty ON cty.iso_country = ent.iso_country
JOIN 
    ref_v2.region_map AS reg ON reg.region_code = cty.region_code
JOIN 
    ref_v2.entity_type_map AS ety ON ety.entity_type_code = ent.entity_type
WHERE  
    reprisk.id_end_date IS NULL
    AND reprisk.factset_id IS NOT NULL
    AND ent.iso_country IN ('SG')
    AND YEAR(r.repr_timeslot_date) = '2020'
    AND r.repr_rating IS NOT NULL
GROUP BY 
    d.[Entity Type], cty.country_desc, reg.region_desc, 
    ent.entity_type, YEAR(r.repr_timeslot_date);

当前output:

数数 实体类型 国家 地区
1个 其他 2020 新加坡 亚洲
2个 其他 2020 新加坡 亚洲
12 其他 2020 新加坡 亚洲
2个 其他 2020 新加坡 亚洲
3个 私人的 2020 新加坡 亚洲
455 民众 2020 新加坡 亚洲
5个 私人的 2020 新加坡 亚洲

必填 Output:

数数 实体类型 国家 地区
8个 私人的 2020 新加坡 亚洲
455 民众 2020 新加坡 亚洲
17 其他 2020 新加坡 亚洲

非常感谢任何建议!

问题出在您的GROUP BY中,您想按计算出的[Entity Type]而不是sym_v1.sym_entity中的分组。

GROUP BY子句更改为:

GROUP BY d.[Entity Type], 
         cty.country_desc, 
         reg.region_desc, 
         YEAR(r.repr_timeslot_date);

在这里,我已经从您的GROUP BY中删除ent.entity_type ,因为您实际上并不想对其进行分组,而是希望对您已经包含的计算列进行分组。

这就是导致您重复的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM