按行顺序连接表

时间:2013-07-12 07:36:13

标签: sql sql-server tsql

SELECT TBL1.C1, TBL1.C2, TBL2.C3, TBL2.C4 
    FROM(
        SELECT 100 C1, 'ABC' C2
        UNION
        SELECT 101 C1, 'XYZ' C2
        UNION 
        SELECT 102 C1, 'PQR' C2 
        UNION
        SELECT 103 C1, 'MNO' C2
        ) TBL1,
        (
        SELECT 1 C3, 'Saving Deposits' C4
        UNION
        SELECT 2 C3, 'Current Deposits' C4
        UNION
        SELECT 3 C3, 'Term Deposits' C4
        )TBL2

以上查询提供以下结果

--------------------------------------------
C1  |  C2 |C3 |     C4
--------------------------------------------
100 | ABC | 1 | Saving Deposits
101 | XYZ | 1 | Saving Deposits
100 | ABC | 2 | Current Deposits
101 | XYZ | 2 | Current Deposits
100 | ABC | 3 | Term Deposits
101 | XYZ | 3 | Term Deposits

但我期待如下结果

--------------------------------------------
C1  |  C2 |C3 |     C4
--------------------------------------------
100 | ABC | 1 |  Saving Deposits
100 | ABC | 2 | Current Deposits
100 | ABC | 3 | Term Deposits
101 | XYZ | 1 | Saving Deposits
101 | XYZ | 2 | Current Deposits
101 | XYZ | 3 | Term Deposits

请帮助我....

3 个答案:

答案 0 :(得分:5)

在查询结尾处添加ORDER BY

ORDER BY TBL1.C1, TBL1.C2, TBL2.C3

所以你的整个查询应该是:

SELECT TBL1.C1, TBL1.C2, TBL2.C3, TBL2.C4 
    FROM(
        SELECT 100 C1, 'ABC' C2
        UNION
        SELECT 101 C1, 'XYZ' C2
        UNION 
        SELECT 102 C1, 'PQR' C2 
        UNION
        SELECT 103 C1, 'MNO' C2
        ) TBL1,
        (
        SELECT 1 C3, 'Saving Deposits' C4
        UNION
        SELECT 2 C3, 'Current Deposits' C4
        UNION
        SELECT 3 C3, 'Term Deposits' C4
        )TBL2
    ORDER BY TBL1.C1, TBL1.C2, TBL2.C3

答案 1 :(得分:4)

试试这个

SELECT TBL1.C1, TBL1.C2, TBL2.C3, TBL2.C4 
    FROM(
        SELECT 100 C1, 'ABC' C2
        UNION
        SELECT 101 C1, 'XYZ' C2
        UNION 
        SELECT 102 C1, 'PQR' C2 
        UNION
        SELECT 103 C1, 'MNO' C2
        ) TBL1,
        (
        SELECT 1 C3, 'Saving Deposits' C4
        UNION
        SELECT 2 C3, 'Current Deposits' C4
        UNION
        SELECT 3 C3, 'Term Deposits' C4
        )TBL2 
Order by TBL1.C2

答案 2 :(得分:2)

您可以使用Order by主要按c2升序排序,其次按c3升序排序。