[英]Count how many times a value occurs across tables
第一次在這里發帖! 真的需要一些幫助。
我有一張有建築物的桌子。 在此表中,有許多屬性,我對其中 2 個感興趣:
- roof_material
- additional_roof_material
在柱頂材料中,有10種不同的屋頂材料,編號為1-10。
相同類型的附加屋頂材料列在 additional_roof_material 中。
例如,我如何計算具有屋頂材料 1 和附加屋頂材料 1 的建築物的次數?
這就是我想要做的,僅適用於每種材料:
Select count(*)
From dbo.40000t where roof_material = 1 and additional_roof_material = 1
我想對每種類型都這樣做,所以我得到了屋頂材料 1、2、3、4、5、6、7、8、9、10 有多少次的完整比較,附加屋頂材料 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.