这里是第一篇文章!确实需要一些帮助。
我有一张带有建筑物的 table 。在这个表中,有很多属性,其中我感兴趣的是2:
- roof_material
- additional_roof_material
柱顶 Material 中,有10种不同的屋顶 Material ,编号为1-10。
additional_roof_material 中列出了相同类型的附加屋顶 Material 。
例如,如何计算屋顶 Material 为 1 的建筑物有多少次附加屋顶 Material 为 1?
这就是我想要做的,只是针对每种 Material :
Select count(*)
From dbo.40000t where roof_material = 1 and additional_roof_material = 1
我想对每种类型执行此操作,这样我就可以完整比较屋顶 Material 1,2,3,4,5,6,7,8,9,10 具有额外屋顶 Material 1,2 的次数, 3、4、5、6、7、8、9、10。
最佳答案
您可以使用带有 case 语句的 sum()
从表中获取排列计数
select
sum((case when roof_material = 1 and additional_roof_material = 1 then 1 else 0 end)) as material_1_1,
sum((case when roof_material = 2 and additional_roof_material = 2 then 1 else 0 end)) as material_2_2
-- etc...
from
dbo.40000t
此查询有一个隐式 group by
子句 - 因为我只选择聚合,所以不需要显式指定 group by
。
更新
根据评论中的要求,如果您希望每个排列作为不同的记录
select
roof_material,
additional_roof_material,
count(1) as num_instances
from
dbo.40000t
-- Not sure if you want permutations where roof_material != additional_roof_material or not.
-- Uncomment these next 2 lines if you do not want those permutations
--where
-- roof_material = additional_roof_material
group by
roof_material,
additional_roof_material
关于mysql - 计算某个值在表中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46707083/