2017-10-12 14 views
2

ここに最初の投稿!本当に助けが必要です。テーブル間で値が何回発生するかをカウントします。

私は建物を持つテーブルがあります。この表では、私は2に興味を持っているの属性の数、そこにある:列屋根材で

- roof_material 
- additional_roof_material 

は、10種類の屋根材は、番号1-10で、そこにあります。

追加の屋根材の同じタイプがadditional_roof_materialに記載されています。

は、どのように私は、例えば、additional_roof_material 1を持って何回建物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は、追加のルテール材料1,2,3,4,5,6,7,8,9,10を有する。

+0

として各順列をしたい場合、あなたは一例を提供することができますか?テーブルと期待される結果を書いてください。 – marco

+1

あなたはmysqlとpostgresqlの両方としてこの質問をタグ付けしました。使用しているデータベース言語を明確にすることはできますか? – Scoots

答えて

2

あなたはcase文このクエリは、暗黙のgroup by句を持ってい

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 

sum()を使用して、テーブルから順列数を取得することができます - 私は私が明示的に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

ありがとう!私はこれが完全に動作すると思います。私はちょうどデータ型がテキストであることに気付きました。 – asguldbrandsen

+0

実際には、戻り値はmaterial_1_1とmaterial_2_2です。キャスト関数が問題を起こしている可能性はありますか? – asguldbrandsen

+0

列をintにキャストしたり、数値を引用符で囲むだけで 'roof_material = '1'のとき - どちらも動作します。 – Scoots

関連する問題