First post here! Really need some help.
I have a table with buildings. In this table, there is a number of attributes, of which I am interested in 2:
- roof_material
- additional_roof_material
In the column roof material, there is 10 different roof materials, with the numbers 1-10.
The same type of additional roof materials are listed in additional_roof_material.
How do I count how many times buildings with roof_material 1, has an additional_roof_material 1, for an instance?
This is what i want to do, just for every material:
Select count(*)
From dbo.40000t where roof_material = 1 and additional_roof_material = 1
I want to do it for each of the types, so i get a complete comparision of how many times roof_material 1,2,3,4,5,6,7,8,9,10 has additional_roof_material 1,2,3,4,5,6,7,8,9,10.
答案 0 :(得分:2)
You can get permutation counts from a table using sum()
with a case statement
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
This query has an implicit group by
clause - because I am only selecting aggregates I do not need to explicitly specify a group by
.
Update
As requested in a comment, if you want each permutation as a distinct record
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