2017-01-03 8 views
0

私はフラグとして機能する一連の列(11個)を自分のデータの末尾に追加しました。ここ複数のSQL Server 2012の結合方法

は、これらのカテゴリのサンプルである: (すなわち、複数のフラグが単一の行に対して表示されることに注意!)

cat2 cat3 cat4 cat5 cat6 cat7 cat8 cat9 cat10 cat11 cat12 
NULL 1  NULL NULL  2 NULL NULL  1 NULL NULL NULL 
NULL NULL NULL NULL NULL NULL  2 NULL NULL NULL NULL 
NULL NULL NULL  1  1 NULL NULL NULL NULL NULL NULL 
NULL  1  1 NULL NULL NULL NULL NULL NULL NULL NULL 
    3 NULL NULL NULL NULL NULL  2 NULL NULL NULL NULL 

私はその説明文字列と対各フラグを別のテーブルを持っています。

ref_id category_position description 
------------------------------------------------ 
1      2 string description 1 
2      2 string description 2 
3      2 string description 3 
1      3 string description 4 
1      4 string description 5 
1      5 string description 6 
1      6 string description 7 
2      6 string description 8 
1      7 string description 9 
1      8 string description 10 
2      8 string description 11 
1      9 string description 12 
1      10 string description 13 
1      11 string description 14 
1      12 string description 15 

私は何とか私のカテゴリは「人間が読める」と定義されているように、nullではないすべてのカテゴリに対して、私の内容を文字列で参加したいです。ここ

は、(ヘッダを含む)のサンプルデータの最初の行に基づいて、私には許容されるであろう可能な結果である:

cat3 [join description]  cat6 [join description]  cat9 [join description] 
    1 string description 4  2 string description 8  1 string description 12 

トラブルは - 私はこのマルチを行う方法がわかりません-part join。私は12回に参加したくない。これはややこしいと思われ、おそらく私が操作している何百万行もの行にはうまくいかないだろう。

+4

これはひどいテーブルデザインです。データを標準化する。 –

+1

テーブルに何度も参加することも、関数を使ってref_idに基づいて値を返すこともできます。課税.... – scsimon

+0

データは生/ライブで提供されており、データのさまざまな側面を要約に含めることを分類しています。ノーマライゼーションは生のテレコムデータであるためオプションではありません。 – ColinMac

答えて

1

ここでは、関数の代替方法があります...結合を行うよりも速くなることはありませんが、限られた用途では便利です。使用中のその後

create function dbo.returnDesc (@ref_id int) 
returns varchar (256) 
as 
begin 
    declare @return varchar(256) 

    set @return = (select [description] from yourTable where ref_id = @ref_id) 

    return @return 
end 

....

select 
    .... 
    dbo.returnDesc(cat2), 
    dbo.returnDesc(cat3), 
    dbo.returnDesc(cat4), 
    .... 
from 
    YourMainTable 
関連する問題