如何形成此SQL查询

时间:2016-01-13 02:52:09

标签: sql sql-server

表1

ID |Name1 | Name2 | Name3
1 |Zaheer | Sachin | Adam
2 |Daniel| Jessica| Kevin

表2

ID| Style| Name| Surname
1 | Bowler| Zaheer | Khan
2 | Keeper | Adam | Gilchrist
3 | Batsman | Sachin | Tendulkar
4 | Actor | Kevin| Spacey
5 | Actress | Jesica | Alba
6 | Actor| Daniel| Craig

结果

Style|Surname|Style|Surname|Style|Surname
Bowler | Khan |Batsman | Tendulkar |Keeper  | Gilchrist
Actor  | Craig|Actress | Alba      |Actor   | Spacey

我尝试使用union,加入但是我得到了必需的结果

2 个答案:

答案 0 :(得分:0)

抱歉:发现问题 - 请不要回答这个问题

      It looks like you can get your result from just Table2:
      select style, surname from table2

答案 1 :(得分:0)

您可以使用条件聚合:

WITH CTE AS(
    SELECT
        t1.ID,
        t2.Style,
        t2.Surname,
        RN = ROW_NUMBER() OVER(PARTITION BY t1.ID ORDER BY t2.ID)
    FROM Table1 t1
    INNER JOIN Table2 t2
        ON t2.Name IN(t1.Name1, t1.Name2, t1.Name3)
)
SELECT
    Style   = MAX(CASE WHEN RN = 1 THEN Style END),
    Surname = MAX(CASE WHEN RN = 1 THEN Surname END),
    Style   = MAX(CASE WHEN RN = 2 THEN Style END),
    Surname = MAX(CASE WHEN RN = 2 THEN Surname END),
    Style   = MAX(CASE WHEN RN = 3 THEN Style END),
    Surname = MAX(CASE WHEN RN = 3 THEN Surname END)
FROM CTE
GROUP BY ID

如果您希望列的顺序为Name1Name2Name3,则需要首先取消忽略Table1

WITH CTE AS(
    SELECT
        t1.ID,
        t2.Style,
        t2.Surname,
        RN = ROW_NUMBER() OVER(PARTITION BY t1.ID ORDER BY t1.No)
    FROM (
        SELECT ID, x.No, x.Name
        FROM Table1
        CROSS APPLY (VALUES
            (1, Name1), (2, Name2), (3, Name3)
        ) x (No, Name)
    ) t1
    INNER JOIN Table2 t2
        ON t2.Name = t1.Name
)
SELECT
    Style   = MAX(CASE WHEN RN = 1 THEN Style END),
    Surname = MAX(CASE WHEN RN = 1 THEN Surname END),
    Style   = MAX(CASE WHEN RN = 2 THEN Style END),
    Surname = MAX(CASE WHEN RN = 2 THEN Surname END),
    Style   = MAX(CASE WHEN RN = 3 THEN Style END),
    Surname = MAX(CASE WHEN RN = 3 THEN Surname END)
FROM CTE
GROUP BY ID