将两个不同条件的计数器放在一起

时间:2013-03-24 20:05:10

标签: sql join count group-by

我需要计算表tweets中的所有retweetsauthors(所有转推也是推文)foreach用户。我的第一个想法很有效:

推文计数器

SELECT a.id, a.name, count(*)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)

转推计数器

SELECT a.id, a.name, count(*)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id AND retweet = TRUE
GROUP BY a.id, a.name
ORDER BY count(*)

...但现在我想把它们放在一起。我想知道是否有更好(更快)的方式:

合并

SELECT a.id, a.name, count(*), (
    SELECT count(*) 
    FROM tweets 
    WHERE fromuser_id = a.id AND retweet = TRUE
)
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)

2 个答案:

答案 0 :(得分:1)

SELECT a.id, a.name, count(*),
       SUM(CASE WHEN retweet = TRUE THEN 1 ELSE 0 END) as retweets_count
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)

答案 1 :(得分:1)

是的,还有更好的方法。使用条件求和:

SELECT a.id, a.name, count(*),
       sum(case when retweet = true then 1 else 0 end) as retweets
FROM authors AS a
INNER JOIN tweets AS t 
ON t.fromuser_id = a.id
GROUP BY a.id, a.name
ORDER BY count(*)