简体   繁体   English

SQL查询中的多个聚合函数

[英]Multiple aggregate functions in SQL query

For this example I got 3 simple tables (Page, Subs and Followers):对于这个例子,我得到了 3 个简单的表(页面、订阅和关注者):

我的三桌

For each page I need to know how many subs and followers it has.对于每个页面,我需要知道它有多少订阅者和关注者。 My result is supposed to look like this:我的结果应该是这样的:

结果

I tried using the COUNT function in combination with a GROUP BY like this:我尝试将 COUNT 函数与 GROUP BY 结合使用,如下所示:

SELECT p.ID, COUNT(s.UID) AS SubCount, COUNT(f.UID) AS FollowCount 
FROM page p, subs s, followers f 
WHERE p.ID = s.ID AND p.ID = f.ID AND s.ID = f.ID 
GROUP BY p.ID

Obviously this statement returns a wrong result.显然这个语句返回了错误的结果。

My other attempt was using two different SELECT statements and then combining the two subresults into one table.我的另一个尝试是使用两个不同的 SELECT 语句,然后将两个子结果合并到一个表中。

SELECT p.ID, COUNT(s.UID) AS SubCount FROM page p, subs s WHERE p.ID = s.ID GROUP BY p.ID

and

SELECT p.ID, COUNT(f.UID) AS FollowCount FROM page p, follow f WHERE p.ID = f.ID GROUP BY p.ID

I feel like there has to be a simpler / shorter way of doing it but I'm too unexperienced to find it.我觉得必须有一种更简单/更短的方法来做到这一点,但我太缺乏经验而找不到它。

Never use commas in the FROM clause.切勿FROM子句中使用逗号。 Always use proper, explicit, standard JOIN syntax.始终使用正确、明确、标准的JOIN语法。

Next, learn what COUNT() does.接下来,了解COUNT()作用。 It counts the number of non-NULL values.它计算非 NULL 值的数量。 So, your expressions are going to return the same value -- because f.UID and s.UID are never NULL (due to the JOIN conditions).因此,您的表达式将返回相同的值——因为f.UIDs.UID永远不会为NULL (由于JOIN条件)。

The issue is that the different dimensions are multiplying the amounts.问题是不同的维度正在乘以数量。 A simple fix is to use COUNT(DISTINCT) :一个简单的解决方法是使用COUNT(DISTINCT)

SELECT p.ID, COUNT(DISTINCT s.UID) AS SubCount, COUNT(DISTINCT f.UID) AS FollowCount 
FROM page p JOIN
     subs s
     ON p.ID = s.ID JOIN
     followers f 
     ON s.ID = f.ID 
GROUP BY p.ID;

The inner joins are equivalent to the original query.内部联接等效于原始查询。 You probably want left join s so you can get counts of zero:您可能想要left join s,以便您可以获得零计数:

SELECT p.ID, COUNT(DISTINCT s.UID) AS SubCount, COUNT(DISTINCT f.UID) AS FollowCount 
FROM page p LEFT JOIN
     subs s
     ON p.ID = s.ID LEFT JOIN
     followers f 
     ON p.ID = f.ID 
GROUP BY p.ID;

Scalar subquery should work in this case.在这种情况下,标量子查询应该有效。

SELECT p.id,
       (SELECT Count(s_uid)
        FROM   subs s1
        WHERE  s1.s_id = p.id) AS cnt_subs,
       (SELECT Count(f_uid)
        FROM   followers f1
        WHERE  f1.f_id = p.id) AS cnt_fol
FROM   page p
GROUP  BY p.id; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM