从3个表中求和值

时间:2009-10-06 06:21:41

标签: sql sql-server-2005

我有3个表,每个表都会显示用户发布消息的记录。

我已经设法将每个用户在每个表上发布消息的次数相加,现在我想为每个用户将这3个单独的值加起来。

以下是我目前管理的内容:

表USERMESSAGE:
SELECT U.SenderID, COUNT(U.SenderID) AS U_NUM FROM USERMESSAGE AS U WHERE U.SenderID != U.ReceiverID GROUP BY U.SenderID

表评论:
SELECT C.UserID, COUNT(C.UserID) AS C_NUM FROM COMMENT AS C GROUP BY C.UserID

表格FRIENDLIST:
SELECT F.UserID, COUNT(F.UserID) AS F_NUM FROM FRIENDLIST AS F WHERE F.ListName = 'News Feed' GROUP BY F.UserID

但并非所有用户都会在所有表中发布,因此某些UserID不会出现在某些表中。

2 个答案:

答案 0 :(得分:2)

选择UserID,SUM(NUM)为总计     FROM(     SELECT USenderID AS UserID,COUNT(bothenderID)AS NUM FROM USERMESSAGE AS U WHERE AREenderID!= U.ReceiverID GROUP BY PROPERenderID

UNION ALL
SELECT C.UserID, COUNT(C.UserID) AS NUM FROM COMMENT AS C GROUP BY C.UserID

UNION ALL
SELECT F.UserID, COUNT(F.UserID) AS NUM FROM FRIENDLIST AS F WHERE F.ListName = 'News Feed' GROUP BY F.UserID
)
GROUP BY UserID

答案 1 :(得分:0)

我会尝试这样的事情

DECLARE @Table1 TABLE(
        UserID INT
)

DECLARE @Table2 TABLE(
        UserID INT
)

DECLARE @Table3 TABLE(
        UserID INT
)

INSERT INTO @Table1 (UserID) SELECT 1
INSERT INTO @Table1 (UserID) SELECT 2
INSERT INTO @Table1 (UserID) SELECT 3

INSERT INTO @Table2 (UserID) SELECT 2
INSERT INTO @Table2 (UserID) SELECT 3

INSERT INTO @Table3 (UserID) SELECT 3

SELECT  ISNULL(CountTable1.CountUserIDTable1,0) +
        ISNULL(CountTable2.CountUserIDTable2,0) +
        ISNULL(CountTable3.CountUserIDTable3,0) CountOverTables,
        UserIDs.UserID
FROM    (
            SELECT  DISTINCT
                    UserID
            FROM    @Table1
            UNION   
            SELECT  DISTINCT
                    UserID
            FROM    @Table2
            UNION   
            SELECT  DISTINCT
                    UserID
            FROM    @Table3
        ) UserIDs LEFT JOIN
        (
            SELECT  UserID,
                    COUNT(UserID) CountUserIDTable1
            FROM    @Table1
            GROUP BY UserID
        ) CountTable1 ON UserIDs.UserID = CountTable1.UserID LEFT JOIN
        (
            SELECT  UserID,
                    COUNT(UserID) CountUserIDTable2
            FROM    @Table2
            GROUP BY UserID
        ) CountTable2 ON UserIDs.UserID = CountTable2.UserID LEFT JOIN
        (
            SELECT  UserID,
                    COUNT(UserID) CountUserIDTable3
            FROM    @Table3
            GROUP BY UserID
        ) CountTable3 ON UserIDs.UserID = CountTable3.UserID