1

我有以下选择结果:

Select t1.ID, t1.Value1 
from t1 
where t1.ID=1

结果:

    ID  Value1
    1   val1
    1   val2
    1   val3
    1   val4

Select t2.ID, t2.Value2 
from t2 where t2.ID = 1

结果 2:

    ID  Value2
    1   val5
    1   val6
    1   val7
    1   val8

我想获得像:

ID  Value1  Value2
1   val1    val5
1   val2    val6
1   val3    val7
1   val4    val8

我怎样才能得到这个结果?

4

3 回答 3

3

我不得不根据你的结果对你想要什么做一些假设,但我认为以下方法会起作用:

;WITH CTE1 AS
(   SELECT  ID, Value1, ROW_NUMBER() OVER(ORDER BY Value1) [RowNumber]
    FROM    t1
), CTE2 AS
(   SELECT  ID, Value2, ROW_NUMBER() OVER(ORDER BY Value2) [RowNumber]
    FROM    t2
)
SELECT  COALESCE(CTE1.ID, CTE2.ID) [ID],
        Value1,
        Value2
FROM    CTE1
        FULL JOIN CTE2
            ON CTE1.ID = CTE2.ID
            AND CTE1.RowNumber = CTE2.RowNumber

FULL JOIN可以替换为LEFT JOININNER JOIN根据您的具体要求。

于 2012-04-04T11:18:03.450 回答
2
SELECT t1.ID, t1.Value1, t2.Value2 FROM t1
INNER JOIN t2 ON t2.ID = t1.ID
WHERE t1.ID=1
于 2012-04-04T11:01:40.097 回答
0

希望外部加入之一可以帮助您解决问题

SELECT t1.ID, t1.Value1, t2.Value2 FROM t1 Right outer Join t2 ON t2.ID = t1.ID WHERE t1.ID=1

于 2012-04-14T07:02:16.980 回答