多个值插入到单个表中

时间:2017-01-20 08:44:52

标签: sql sql-server multiple-columns multiple-value

我需要帮助查询两个表成为一个表

第一个表格 Tbl_Project:

|ID     | Category  | Freq_Project|
|-------|---------- |-------------|
|12001  |   x_GM    | 1           |
|12001  |   x_PP    | 1           |
|12001  |   x_RI    | 1           |
|12001  |   x_SS    | 3           |

第二个表格, Tbl_Activity:

|ID     | Category  | Freq_Activity|
|-------|---------- |--------------|
|12001  |   x_GM    |4             |
|12001  |   x_PP    |3             |
|12001  |   x_SA    |2             |
|12001  |   x_RI    |2             |

而且,我希望结果看起来像这样

|ID     | Category  | Freq_Activity | Freq_Project|
|-------|---------- |---------------|-------------|
|12001  |   x_GM    |   4           |   1         |
|12001  |   x_PP    |   3           |   1         |
|12001  |   x_SA    |   2           |   **Null**  |
|12001  |   x_RI    |   2           |   1         |
|12001  |   x_SS    |   **Null**    |   3         |

我该如何进行此查询?

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码将结果插入目标表。

Insert INTO ResultTable(ID,Category,Freq_Activity,Freq_Project,Tbl_Project)
Select ISNULL(P.ID,A.ID),ISNULL(P.Category,A.Category),A.Freq_Activity,P.Freq_Project,Tbl_Project
from Tbl_Project P
FULL OUTER JOIN Tbl_Activity A
ON P.ID=A.ID
AND P.Category = A.Category

答案 1 :(得分:0)

完整联接看起来像这样

SELECT ISNULL(P.ID,A.ID),ISNULL(P.Category,A.Category),P.Freq_Projeckt,A.Freq_activity
FROM Tbl_Project P
FULL OUTER JOIN Tbl_Activity A
ON A.ID=P.ID AND A.Category=P.Category

答案 2 :(得分:0)

使用Union:

        SELECT distinct ID,Category,max(Freq_Activity)Freq_Activity,
        max(Freq_Project)Freq_Project  from
        (
        SELECT ID,Category,Freq_Project,null 'Freq_Activity'
        FROM Tbl_Project TP
        union
        SELECT ID,Category,null 'Freq_Project',Freq_Activity
        FROM Tbl_Activity TP
        )a
        group by ID,Category