将父表列值附加到sql中的子表列

时间:2016-03-09 06:34:05

标签: sql-server

假设我有两个表,如下所示:

表1

ID           Name
------------------
1            Adam
2            Eve

表2

ID           FK_ID (Table 1)          Name
--------------------------------------------
1                   1                 Chris
2                   1                 Austin
3                   1                 Steve
4                   2                 Charles
5                   2                 Erik
6                   2                 Austin

必填表格作为结果

ID          Name
-----------------
1           Chris
2           Austin Adam
3           Steve
4           Charles
5           Erik
6           Austin Eve

请注意,在结果表格中,我想重复一次" Austin"附上" Adam / Eve"来自父表(即表1),取决于" FK_ID"。我想在SQL中这样做。任何想法/帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:4)

您可以East使用GROUP BY Name检查姓名,然后count(*) > 1正确添加LEFT JOIN名称

示例数据

T1

<强>查询

CREATE TABLE Table1
    ([ID] int, [Name] varchar(4));

INSERT INTO Table1
    ([ID], [Name])
VALUES
    (1, 'Adam'),
    (2, 'Eve');

CREATE TABLE Table2
    ([ID] int, [FK_ID] int, [Name] varchar(7));

INSERT INTO Table2
    ([ID], [FK_ID], [Name])
VALUES
    (1, 1, 'Chris'),
    (2, 1, 'Austin'),
    (3, 1, 'Steve'),
    (4, 2, 'Charles'),
    (5, 2, 'Erik'),
    (6, 2, 'Austin');

<强>输出

SELECT
    T2.ID,
    T2.Name + CASE WHEN T3.Name IS NOT NULL THEN ' ' + T1.Name ELSE '' END as Name
FROM Table2 T2
INNER JOIN Table1 T1 ON T2.[FK_ID] = T1.id
LEFT JOIN (SELECT Name FROM Table2 GROUP BY Name HAVING COUNT(*) > 1) T3 ON T2.Name = T3.Name

答案 1 :(得分:2)

您可以使用窗口计数来确定名称是否重复:

SELECT t2.ID, 
       CONCAT(t2.Name,
          IIF(COUNT(t2.Name) OVER(PARTITION BY t2.Name) > 1, 
              COALESCE(' ' + t1.Name, ''), 
              ''))
FROM TABLE2 AS t2
LEFT JOIN TABLE1 AS t1 ON t2.FK_ID = t1.ID

答案 2 :(得分:0)

    SELECT ID,NAME
    FROM TABLE2
    WHERE NAME NOT IN (
        SELECT NAME
        FROM TABLE2
        GROUP BY NAME
        HAVING COUNT(*) >1 )
    UNION
    SELECT A.ID AS ID,A.NAME+' '+B.NAME AS NAME
    FROM TABLE2 AS A INNER JOIN TABLE1 AS B
    ON A.FK_ID = B.ID
    WHERE NAME IN (
        SELECT NAME
        FROM TABLE2
        GROUP BY NAME
        HAVING COUNT(*) >1 )
   ORDER BY ID

使用union来处理两个组的逻辑。