根据SQL Server

时间:2017-05-20 12:52:33

标签: sql sql-server tsql sql-server-2014

以下是表格设计

CustId   Ver    VersionNo   Version ResNO   Res     Name    Path
---------------------------------------------------------------------------
2        VF         2       V2        1     Low     temp    a/PV_7_temp.pdf
2        VF         2       V2        2     High    temp    a/temp/temp.pdf

如果用户输入路径为'a/PV_7_temp.pdf',则结果应为:

CustId  Path
--------------------------
2        VF                  ---ver
2        V2                  ---version
2        High                ----Res
2        a/PV_7_temp.pdf     -----path

如果用户输入路径为'a/temp/temp.pdf',则结果应为:

CustId  Path
-------------------------
2        VF
2        V2
2        Low
2       a/temp/temp.pdf

请帮助我在SQL Server 2014中获得所需的结果

1 个答案:

答案 0 :(得分:2)

使用cross apply(values ...)取消对数据的取消投放:

declare @Path varchar(128) = 'a/temp/temp.pdf';

select t.CustId, u.Path
from t
  cross apply (values (1,Ver),(2,Version),(3,Res),(4,Path)) u(Ordinal, Path)
where t.Path = @Path
order by t.CustId, u.Ordinal

根据您的示例,您确实需要order by的内容。您是否有理由不想包含指定每个值来源的列?

rextester演示:http://rextester.com/JEBMGH56691

返回:

+--------+-----------------+
| CustId |      Path       |
+--------+-----------------+
|      2 | VF              |
|      2 | V2              |
|      2 | High            |
|      2 | a/temp/temp.pdf |
+--------+-----------------+