T-Sql多个self-Joins返回单个主值

时间:2016-04-29 09:29:05

标签: tsql sql-server-2012 inner-join self-join

如果我有一张如下表格

| COL1 | COL2 | COL3 | COL4 |
-----------------------------
|  A   |  B   | *null* | *null* |
| *null* |  B   |  C   | *null* |
| *null* | *null* |  C   |   D  |

我有一个存储过程,可以接受四个参数,如此

CREATE PROCEDURE [dbo].[usp_Testing]
    @value1 varchar(1) = NULL,
    @value2 varchar(1) = NULL,
    @value3 varchar(1) = NULL,
    @value4 varchar(1) = NULL

如果一次只传入一个值,我想从COL1获得值A. 例如如果@ value4以值'D'传递,那么我想通过自行加入第3行得到A,这样我们就可以得到C得到row2 C得到使用B得到row1得到我们A 目前我做的事情(手工操作,所以可能没有完全运行)这个

DECALRE @use varchar(1)
IF(@Value1 IS NOT NULL OR @Value2 IS NOT NULL)
    SELECT TOP 1 @Use = COL1 FROM TAB t1 
    WHERE COL1 = @Value1 or COL2 = @Value2
ELSE IF (@Value3 IS NOT NULL)
    SELECT TOP 1 @Use = COL1 FROM TAB t1 
    INNER JOIN TAB t2 ON t1.COL2 = t2.COL2
    WHERE COL3 = @Value3
ELSE IF (@Value4)
    SELECT TOP 1 @Use = COL1 FROM TAB t1 
    INNER JOIN TAB t2 ON t1.COL2 = t2.COL2
    INNER JOIN TAB t3 ON t2.COL3 = t3.COL3
    WHERE COL4 = @Value2

这有效,但是有没有办法缩短它? 我正在使用sql server 2012

谢谢, 尼克

1 个答案:

答案 0 :(得分:1)

如下所示

SELECT t1.col1, t1.col2, t2.col3, t3.col4
FROM tab t1
JOIN tab t2 ON t1.col2 = t2.col2
JOIN tab t3 ON t2.col3 = t3.col3
WHERE 
  COALESCE( @Value1, t1.col1 ) = t1.col1 AND 
  COALESCE( @Value2, t2.col2 ) = t2.col2 AND 
  COALESCE( @Value3, t3.col3 ) = t3.col3 AND 
  COALESCE( @Value4, t3.col4 ) = t3.col4  
GROUP BY t1.col1, t1.col2, t2.col3, t3.col4