簡體   English   中英

SQL:將COUNT和GROUP與SUM結合查詢

[英]SQL: SUM the COUNT and GROUP to Combine Queries

有沒有將這兩個查詢組合成一個查詢,因此結果是:

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

結果= 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; 等等..

在此先感謝您的幫助。

嘗試這個:

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

效率不高,但簡單易行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM