【问题标题】:Calculating Grouped Counts while using Case Statement使用案例语句时计算分组计数
【发布时间】:2020-12-22 17:08:10
【问题描述】:

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

查询产生了我想要的输出,但是我无法让查询将计数分组到我选择的类别中。我最初在主选择查询中有 CASE 语句,但在其他地方找到类似的问题后,我将其移至子查询,但我遇到了同样的问题。查询下面的示例输出:

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);

当前输出:

Count Entity Type Year Country Region
1 Other 2020 Singapore Asia
2 Other 2020 Singapore Asia
12 Other 2020 Singapore Asia
2 Other 2020 Singapore Asia
3 Private 2020 Singapore Asia
455 Public 2020 Singapore Asia
5 Private 2020 Singapore Asia

所需输出:

Count Entity Type Year Country Region
8 Private 2020 Singapore Asia
455 Public 2020 Singapore Asia
17 Other 2020 Singapore Asia

非常感谢任何建议!

【问题讨论】:

  • 仅供参考:它是一个案例表达式而不是语句。

标签: sql-server group-by count sql-server-2012 case


【解决方案1】:

问题出在您的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,因为您实际上并不想对其进行分组,而是希望对已包含的计算列进行分组。

这就是导致重复的原因。

【讨论】:

  • 谢谢,看来我只是没有发现重复的行!
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2023-03-04
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 2019-06-24
相关资源
最近更新 更多