2017-10-12 48 views
2

第一篇文章!真的需要一些幫助。指望有多少次的值跨表發生在這裏

我有建築物的表。在該表中,有多個屬性,其中我在2很感興趣的:

- roof_material 
- additional_roof_material 

在列屋頂材料,有10種不同的屋頂材料,編號爲1-10。

additional_roof_material中列出了相同類型的附加屋頂材料。

我怎麼算,有多少次幢樓roof_material 1,有一個additional_roof_material 1,一個實例?

這就是我想做的事情,只是每種材料:

Select count(*) 
From dbo.40000t where roof_material = 1 and additional_roof_material = 1 

我想這樣做,對每種類型的,所以我得到roof_material 1,2多少次的一個完整的對比, 3,4,5,6,7,8,9,10有additional_roof_material 1,2,3,4,5,6,7,8,9,10。

+0

你能提供一個例子嗎?請寫一張表格和預期的結果。 – marco

+1

您已經標記了這個問題既是MySQL和PostgreSQL - 你可以澄清的數據庫語言被使用嗎? – Scoots

回答

2

您可以從表中使用sum()用case語句

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 
+0

謝謝!我認爲這會很好地工作。我剛剛意識到數據類型是文本,是否會引起任何問題,如果我投如int,總和()內? – asguldbrandsen

+0

實際上,它只返回:1表示material_1_1,2表示material_2_2 ....鑄造函數是否可能導致問題? – asguldbrandsen

+0

您可以將列轉換爲int,或者只需在「roof_material ='1''時將引號包含在引號中,即可以使用。 – Scoots

相關問題