0

マトリックス スタイルのレポートのクエリを作成するのに助けが必要です。

私のデータは次の形式です

id    body_part   incident_type1  incident_type2   incident_type3 
1     head        PPE             null             null 
2     ankle       Unsafe Act      Facility         null
3     hand        null            null             null
4     head        Facility        PPE              Unsafe Act

行が体の部分になり、列がインシデントの種類になるようにします。Incident_type1 が null の場合、「n/a」列にカウントが必要です。ただし、incident_type2 および/または 3 が null の場合、それらを "n/a" 列に含めたくありません。

            Facility    Unsafe Act    PPE     N/A
ankle        1            1            0       0
hand         0            0            0       1
head         1            1            2       0
4

2 に答える 2

0

これを行う 1 つの方法を次に示します。

select body_part
  , Facility = sum(case when incident_type1 = 'Facility' or incident_type2 = 'Facility'  or incident_type3 = 'Facility' then 1 else 0 end)
  , [Unsafe Act] = sum(case when incident_type1 = 'Unsafe Act' or incident_type2 = 'Unsafe Act'  or incident_type3 = 'Unsafe Act' then 1 else 0 end)
  , PPE = sum(case when incident_type1 = 'PPE' or incident_type2 = 'PPE'  or incident_type3 = 'PPE' then 1 else 0 end)
  , [N/A] = sum(case when incident_type1 is null then 1 else 0 end)
from Incidents
group by body_part
order by body_part

demo を使用した SQL Fiddle

これは、既知のインシデント タイプと、同じ行に同じインシデント タイプが複数回含まれないことを前提としています。

于 2013-06-03T09:09:24.657 に答える