0

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

第一个表,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         |

我应该怎么做这个查询?

4

3 回答 3

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
于 2017-01-20T09:02:02.737 回答
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
于 2017-01-20T08:55:41.653 回答
0

使用联合:

        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
于 2017-01-20T09:29:22.003 回答