SQL:Sub Query用于过滤Query的结果

时间:2015-06-25 09:33:44

标签: sql sql-server

SELECT SUM(imps.[Count]) AS A , COUNT (imps.Interest_Name) AS B, ver.Vertical_name
FROM Impressions imps
INNER JOIN Verticals ver 
ON imps.Campaign_id = ver.Campaign_id
WHERE ver.Vertical_name = 'Retail' OR ver.Vertical_name = 'Travel'
GROUP BY imps.Interest_Name, ver.Vertical_name;

上述查询返回记录为:

 A  B   Vertical_name
 6  6   Retail
 3  2   Retail
 7  1   Travel
13  10  Travel

我想修改此查询以获得结果,例如:

 A  B   Vertical_name
 9  8   Retail
 20 11  Travel

那是通过垂直名称进一步分组并取出列A和B的SUM。我想这必须通过子查询来完成购买不确定如何?

3 个答案:

答案 0 :(得分:2)

只需按vertical_name分组,然后从您的imps.Interest_Name移除GROUP BY,因为您正在执行COUNT (imps.Interest_Name)

SELECT SUM(imps.[Count]) AS A , COUNT (imps.Interest_Name) AS B, ver.Vertical_name
FROM Impressions imps
INNER JOIN Verticals ver 
ON imps.Campaign_id = ver.Campaign_id
WHERE ver.Vertical_name = 'Retail' OR ver.Vertical_name = 'Travel'
GROUP BY ver.Vertical_name;

答案 1 :(得分:1)

你的分组由两列组成,即imps.Interest_Name,ver.Vertical_name。 我修改了你的SQL我觉得这些对你有用。

{
    "template" : "wheepl",
    "order" : 10,
    "mappings" : {
        "couchbaseCheckpoint" : {
            "_source" : {
                "includes" : ["doc.*"]
            },
            "dynamic_templates": [
                {
                    "store_no_index": {
                        "match": "*",
                        "mapping": {
                            "store" : "no",
                            "index" : "no",
                            "include_in_all" : false
                        }
                    }
                }
            ]
        },
        "couchbaseDoc" : {
            "_timestamp" : {
                "enabled" : true,
                "store" : true
            },
            "properties" : {
                "meta" : {
                    "type" : "object",
                    "include_in_all" : false
                },
                "doc" : {
                    "type" : "object",
                    "include_in_all" : false,
                    "updateEpoch" : {
                        "type" : "date",
                        "format" : "date_time",
                        "numeric_resolution" : "seconds"
                    }
                }
            }
        }
    }
}

谢谢..

答案 2 :(得分:1)

尝试此查询

SELECT SUM(imps.[Count]) AS A , COUNT (imps.Interest_Name) AS B, ver.Vertical_name
FROM Impressions imps
INNER JOIN Verticals ver 
ON imps.Campaign_id = ver.Campaign_id
WHERE ver.Vertical_name = 'Retail' OR ver.Vertical_name = 'Travel'
GROUP BY  ver.Vertical_name;