2016-09-22 3 views
0

これが重複していると私は驚くことはありませんが、このバリエーションをテーマで見つけることができませんでした。列挙型と対応する値をSQLの別の列に変換します

2つの列を持つテーブルがあります.1つはデータ型を示し、もう1つは対応する値を示します。 SELECTを使ってこれを変換して、列挙されたそれぞれの "型"が値によって設定された独自の列になるようにします。

Table PersonInfo 
InfoID PersonID AttributeType AttributeValue 
    1   1   email  [email protected] 
    2   1   dept  research 
    3   2   email  [email protected] 
    4   2   dept  engineering 
    5   3   email  [email protected] 

SELECT結果は次のようになります。

PersonID email    dept 
     1 [email protected] research 
     2 [email protected] engineering 
     3 [email protected] NULL 

あなたが見ることができるように、InfoID指数はもはや必要ありません。

私の場合、AttributeType列の潜在的な値を知っているので、完全に動的である必要はありません。ここで

は、私が試したものです:

SELECT DISTINCT PersonID, 
     CASE AttributeType WHEN 'email' THEN AttributeValue ELSE null END as email 
     CASE AttributeType WHEN 'dept' THEN AttributeValue ELSE null END as dept 

私はなぜこれが失敗しているけど、私は私が希望通りに動作させるために何をすべきかわかりません。

+0

別の方法として、電子メールと部門を別々の列に分割する方法があります。 2つ以上の目的に役立つ列は、しばしば扱いにくいです。データベース設計を変更することができない場合があります。 –

+0

この回答:http://stackoverflow.com/questions/16916470/convert-row-value-in-to-column-in-sql-server-pivot私が欲しいものを正確に行うようです。 –

答えて

1
select 
personid, 
max(case when attributetype='email' then AttributeValue end) email, 
max(case when attributetype='dept' then AttributeValue end) dept 
from 
table 
group by personid 
関連する問題