SQL Server 2012多重连接技术

时间:2017-01-03 19:13:08

标签: sql join sql-server-2012

我已将一系列列(其中11个)附加到我的数据中,每个列都充当标记。

以下是这些类别的示例: (请注意,单行可以显示多个标志!)

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

我想以某种方式将我的字符串描述加入到非空的每个类别中,以便我的类别是“人类可读的”并定义。

根据第一行样本数据(包括标题),以下是我可以接受的可能结果:

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

麻烦 - 我不知道如何进行多部分联接。我不想加入12次,因为这似乎很草率,也许不适用于我正在操作的数百万行。

1 个答案:

答案 0 :(得分: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