如何将两个SELECT查询与不同的WHERE和GROUP BY子句合并

时间:2014-12-08 18:35:26

标签: c# sql google-bigquery

我有两个问题如下:

SELECT 
    Actor2Code, 
    COUNT(Actor2Code) AS playermentions 
FROM [events] 
WHERE 
    Year=" + Date + " 
    AND 
    (
        (
            (Actor1CountryCode ='" + mainPlayer1 + "') 
            AND 
            (Actor2CountryCode != '" + mainPlayer1 + "')
        ) 
        OR 
        (
            Actor1CountryCode='" + mainPlayer2 + "' 
            AND 
            Actor2CountryCode !='" + mainPlayer2 + "'
        )
    ) 
GROUP BY Actor2Code;

SELECT 
    Actor1Code, 
    COUNT(Actor1Code) AS playermentions 
FROM [events] 
WHERE 
    Year=" + Date + " 
    AND 
    (
        (
            (Actor2CountryCode ='" + mainPlayer1 + "') 
            AND 
            (Actor1CountryCode != '" + mainPlayer1 + "')
        ) 
        OR 
        (
            Actor2CountryCode='" + mainPlayer2 + "' 
            AND 
            Actor1CountryCode !='" + mainPlayer2 + "'
        )
    ) 
GROUP BY Actor1Code

我将结果合并到c#中,我有一个演员列表和另一个提及的列表。如何将这两个查询合二为一,这样我就有一个演员列表而没有重复的演员代码?一些参与者在两个查询的响应中具有不同的提及次数。我想编写一个查询来合并这两个查询的结果,并给我一个列表,其中包括不同的actor1codes和actor2codes以及提及的数量(对于我需要提及的数量总和的重复值)

1 个答案:

答案 0 :(得分:0)

这几乎可以,但您必须手动删除重复项。

SELECT ActorCode, playermentions FROM

(SELECT 
    Actor2Code as ActorCode, 
    COUNT(Actor2Code) AS playermentions 
FROM [events] 
WHERE 
    Year=" + Date + " 
    AND 
    (
        (
            (Actor1CountryCode ='" + mainPlayer1 + "') 
            AND 
            (Actor2CountryCode != '" + mainPlayer1 + "')
        ) 
        OR 
        (
            Actor1CountryCode='" + mainPlayer2 + "' 
            AND 
            Actor2CountryCode !='" + mainPlayer2 + "'
        )
    ) 
GROUP BY Actor2Code),
(SELECT 
    Actor1Code as ActorCode, 
    COUNT(Actor1Code) AS playermentions 
FROM [events] 
WHERE 
    Year=" + Date + " 
    AND 
    (
        (
            (Actor2CountryCode ='" + mainPlayer1 + "') 
            AND 
            (Actor1CountryCode != '" + mainPlayer1 + "')
        ) 
        OR 
        (
            Actor2CountryCode='" + mainPlayer2 + "' 
            AND 
            Actor1CountryCode !='" + mainPlayer2 + "'
        )
    ) 
GROUP BY Actor1Code);