SQL STUFF和CASE表达式以及连接表

时间:2016-11-14 14:14:55

标签: sql-server case ssms for-xml-path

第一次发表海报,如果我没有按要求详细说明一切,请道歉!有一个很好的搜索任何类似的问题,但无法找到。

我被要求写一个查询,显示通过坐在同一车辆中链接到其他客户的客户 -

Ref  Ref2   
1       2
1       3
1       4
2       1
2       3
2       4 

简单地说,客户端1,2,3和4都在同一车辆中,因此在表格中有一行将它们连接在一起。

我的任务是添加到报告中,链接文件的详细信息,与我的查询的其余部分在同一行中。我通过使用stuff函数完成了这个,从另一个问题找到:

select distinct r.ref
, stuff(
(select ','+r2.ref2 as [text()]
from related r
where r2.ref = r.ref 
for xml path ('')
),1,1,' ') as [linked]
from related r2

显示在第1行:2,3,4,这很好。

我需要做的是相同的,但要使用与上述相同的理论详细说明客户在车辆中的位置,例如

Ref |Linked | Driver/Passenger
1 |   2,3,4 |  D,P,P,P

这是查询,因为我使用CASE表达式对其进行了调整 - 我认为我的联接是其中一个问题,并试图包含在其他地方,但无济于事:

select distinct r.ref
, stuff(
(select ','+CASE WHEN s.status = 'DRV' THEN 'D' WHEN 
s.status = 'PASVEC' THEN 'P' WHEN s.status = 'OWNND' THEN 'P' ELSE '' END [text()]
from status s
where s.ref = r.ref2 -- Looking at the ref of the linked case
for xml path ('')),1,1,' ') as [D/P]
from related r

编辑:

我得到的输出是所有相关案例的列表,即

Ref | D/P
1   | D
2   | P
3   | P
4   | P

没有错误输出。

我还在from语句中尝试了内连接。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果您只是想要另一个人的主要/关联状态的表示,那么你不能只是略有不同<a href="#m1" class="sw">CL1<a/> <a href="#m2" class="sw active">CL2<a/> <div class="sw m1>HELLO1</div> <div class="sw m2 active>HELLO2</div> 吗?

$('a.sw').on('click', function() { 
    var nohash = $(this).attr('href').replace('#', '');
    if ( !$( this ).hasClass( "active" ) ) {
        $('.sw').each(function() { 
            if($(this).hasClass('active')) { 
                $(this).removeClass('active');
            } else { 
                nohash.addClass('active');
            }
        });
    }
});

$( 'a.sw' ).on( 'click', function() {
   $('div.sw').removeClass( 'active' );
   $(this).href().replace('#', '').addClass( 'active' )
});

输出:

FOR XML