我想知道是否有可能获得行值之和,其中某些行是不同的名称。我知道我需要使用一个总和,但不确定如何仅在行名匹配的地方进行总和。
这是我当前正在使用的查询
SELECT b.visits, b.country FROM urls_analytics AS a
JOIN analytics AS b ON a.urls_slug = b.slug
WHERE creator_user_id='some user id'
AND a.urls_slug='some slug'
AND b.continent="NA"
AND b.visit_date >= (DATE(NOW()) - INTERVAL 7 DAY)
这是我现在查询的输出。
visits country
5 Canada
10 Canada
15 Canada
5 Canada
5 United States
10 United States
5 Austraillia
这就是我希望查询返回结果的方式
visits country
35 Canada
15 United States
5 Austraillia
答案 0 :(得分:1)
仅group by个国家/地区名称
SELECT sum(b.visits) sum_visits, b.country FROM urls_analytics AS a
JOIN analytics AS b ON a.urls_slug = b.slug
WHERE creator_user_id='some user id'
AND a.urls_slug='some slug'
AND b.continent="NA"
AND b.visit_date >= (DATE(NOW()) - INTERVAL 7 DAY)
group by b.country;
答案 1 :(得分:1)
您可以使用GROUP BY
子句对country
字段进行汇总,并使用SUM
函数对值求和:
SELECT SUM(b.visits) AS visits, b.country FROM urls_analytics AS a
JOIN analytics AS b ON a.urls_slug = b.slug
WHERE creator_user_id='some user id'
AND a.urls_slug='some slug'
AND b.continent="NA"
AND b.visit_date >= (CURDATE() - INTERVAL 7 DAY)
GROUP BY b.country
请注意,您可以将CURDATE()
用作DATE(NOW())
的简写
答案 2 :(得分:0)
您需要使用“ group by”。
SELECT
SUM(b.visits),
b.country
FROM
urls_analytics AS a JOIN analytics AS b ON a.urls_slug = b.slug
WHERE
creator_user_id='some user id' AND
a.urls_slug='some slug' AND
b.continent="NA" AND
b.visit_date >= (DATE(NOW()) - INTERVAL 7 DAY)
GROUP BY b.country