我正在努力使用以下SQL: 我有一个表有一个site_id和一个站点的引用域。我试图通过引荐来源和网站简单计算出现次数,然后计算一个网站的所有引荐来源的总数。
在我的结果中,计数和网站总数不正确。计数应该是一半,例如对于网站ID 1,Google和亚马逊的计数应为10,网站ID 2的总数应为18。 我有什么想法可能做错了吗?
SELECT site_id, I.referrer_domain AS referrer_domain, COUNT(*) AS items, t.site_total
FROM qVisitor_Tracking_1 as I,
(SELECT COUNT(1) AS site_total
FROM `qVisitor_Tracking_1`
WHERE `referrer_domain` != '' group by site_id) AS T
WHERE `referrer_domain` != ''
GROUP BY `site_id`, referrer_domain
site_id referrer count site total
1 amazon 20 24
1 google 20 24
2 amazon 12 24
2 google 18 24
答案 0 :(得分:2)
如果我理解您的要求,您似乎缺少将子查询加入主表的ON子句。
SELECT I.site_id,
I.referrer_domain AS referrer_domain,
COUNT(*) AS items,
T.site_total
FROM qVisitor_Tracking_1 as I
INNER JOIN
(
SELECT site_id,
COUNT(1) AS site_total
FROM qVisitor_Tracking_1
WHERE referrer_domain != ''
GROUP BY site_id
) AS T
ON I.site_id = T.site_id
WHERE referrer_domain != ''
GROUP BY I.site_id, referrer_domain, T.site_total
答案 1 :(得分:1)
在mysql中,您可以使用GROUP BY
修饰符 WITH ROLLUP
:
SELECT site_id, referrer_domain COUNT(*) AS items
FROM qVisitor_Tracking_1
WHERE referrer_domain != ''
GROUP BY site_id, referrer_domain WITH ROLLUP
它应该给出这样的结果:
site_id referrer items
1 amazon 7
1 google 13
1 NULL 20
2 amazon 6
2 google 9
2 NULL 15
NULL NULL 35
请参阅:http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html
答案 2 :(得分:0)
你在I和T之间没有直接或间接的联合(在哪个部分)。所以你只有乘法
FROM qVisitor_Tracking_1 as I,
(SELECT COUNT(1) AS site_total
FROM `qVisitor_Tracking_1`
WHERE `referrer_domain` != '' group by site_id) AS T
WHERE `referrer_domain` != ''