SQL:将COUNT和GROUP与SUM结合查询

时间:2013-03-13 18:43:20

标签: mysql sql select count sum

是否有人将这两个查询合并为一个查询,结果是:

ChannelId   | ContentType | ContentTypeCount | SumOfAllContentTypes
  100       | link        | 59               | 179
  100       | photo       | 49               | 179
  100       | status      | 2                | 179
  100       | video       | 4                | 179
  101       | link        | 15               | 179
  101       | status      | 50               | 179

以下是我目前使用的查询:

SELECT
COUNT(posts.id)
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1

result = 179

和..

SELECT
posts.channel_id,
posts.contenttype,
COUNT(posts.contenttype) as contenttypecount
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1
GROUP BY posts.channel_id, posts.contenttype

结果= 100 |链接| 59;等。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

试试这个:

select A.*, B.*
from (
  SELECT
  posts.channel_id,
  posts.contenttype,
  COUNT(posts.contenttype) as contenttypecount
  FROM posts
  INNER JOIN channels ON channels.id = posts.channel_id
  WHERE channels.site_id = 1003
  AND channels.channel_type_id = 1
  GROUP BY posts.channel_id, posts.contenttype
) A
join (
  SELECT
  COUNT(posts.id) as Total
  FROM posts
  INNER JOIN channels ON channels.id = posts.channel_id
  WHERE channels.site_id = 1003
  AND channels.channel_type_id = 1
) B on 1=1

效率不高,但简单易行。