使用SQL Server 2012-我试图从数据库中完成不同实体的计数,按其国家和地区分组;地区以及他们所属的公司类型。后一部分就是问题所在——;类型";,我试图将它们分为三类:公共、私人,并使用案例陈述将所有其他内容都归入"其他"。
查询会产生我想要的输出,但是我无法让查询将计数分组到我选择的类别中。我最初在主选择查询中有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);
电流输出:
计数 | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 2 | 12 | 2 | 3 | 455 | 5 |
问题出在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
,因为你实际上不想在它上分组,你想在你已经包含的计算列上分组。
这就是导致重复的原因。