SQL Server上的数据透视动态列

时间:2015-07-30 15:21:19

标签: sql sql-server pivot

我有3张这样的表,

1:LoanPrograms

id                                      Name               
------------------------------------    --------------------------------
9C374820-357B-46FE-B509-003B9DB1507F    FHA 30 YEAR FIXED HIGH BALANCE
B8A76A63-D867-4D89-9749-018238C446B5    JUMBO 10/1 YR ARM BARCLAYS
458AA688-AF12-438D-AFA3-01C804E9C6F6    JUMBO EXPANDED PLUS 30 YEAR FIXED
D8D6D621-6D14-493B-AAA8-02285EC9A54D    z_Test_FHA_30_Year_SL
8C735061-3CA2-4065-ABBF-03CF4234BD36    CONF 15 YR 105 DU REFI PLUS

2:频道

Id                                      Name
------------------------------------    -------------
DCBAD5E8-91B1-4EC6-8545-4265367EFFCD    Broker
0BC94231-C174-41DE-A9C5-980C7834B55A    Correspond
6000F785-0D98-4DA6-8431-B13F01295EFE    Retail

3:LoanProgramChannels

Loanprogram_Id                           Channel_id
------------------------------------   ------------------------------------
9C374820-357B-46FE-B509-003B9DB1507F    DCBAD5E8-91B1-4EC6-8545-4265367EFFCD
9C374820-357B-46FE-B509-003B9DB1507F    0BC94231-C174-41DE-A9C5-980C7834B55A
458AA688-AF12-438D-AFA3-01C804E9C6F6    0BC94231-C174-41DE-A9C5-980C7834B55A
D8D6D621-6D14-493B-AAA8-02285EC9A54D    6000F785-0D98-4DA6-8431-B13F01295EFE

我必须显示如下结果。列出所有贷款计划,如果贷款计划在“LoanProgramChannel”表格中有特定渠道的条目,则将其标记为“Y”,否则为“N”。我对SQL很新,我知道我必须使用pivot函数来实现这些。但不确定我该如何实现呢?

Loan Program Name                     Broker   Correspond  Retail
--------------------                 -------  ---------   -------
FHA 30 YEAR FIXED HIGH BALANCE       y             y          N
JUMBO 10/1 YR ARM BARCLAYS           N             N          N
JUMBO EXPANDED PLUS 30 YEAR FIXED    N             y          N
z_Test_FHA_30_Year_SL                N             N          Y
CONF 15 YR 105 DU REFI PLUS          N             N          N

1 个答案:

答案 0 :(得分:0)

请尝试此查询。它使用SQL PIVOT以及一个简单的ISNULL检查来获取错误值

    SELECT 
        [Loan Program Name],
        ISNULL([Broker],'N') as [Broker],
        ISNULL([Correspond],'N') as [Correspond],
        ISNULL([Retail],'N') as [Retail]
    FROM
        (
            SELECT 
                L.Name as [Loan Program Name],
                'Y' as v,C.Name  as [ChannelType] 
            FROM LoanPrograms L LEFT JOIN LoanProgramChannels LC 
                ON L.id =LC.Loanprogram_Id  LEFT JOIN Channels C 
                ON C.id=LC.Channel_id
        ) S
        PIVOT
        (
            MAX(v) FOR [ChannelType] IN ([Broker],[Correspond],[Retail])
        )piv

我还创造了一个小提琴:http://sqlfiddle.com/#!6/3e6c6/2