MySQL嵌套AVG over SUM

时间:2014-09-25 10:56:27

标签: mysql sql

我的表有列合作伙伴,帖子,后变异

现在我想知道每个合作伙伴平均每个帖子有多少个帖子。我尝试了以下内容,但它无法正常工作

SELECT partner, 
COUNT(DISTINCT post), 
COUNT(DISTINCT postvariation), 
AVG(COUNT(DISTINCT post,postvariation)) 
FROM posts 
GROUP BY partner 
ORDER BY `id` DESC;

3 个答案:

答案 0 :(得分:3)

以下是您要查找的查询:

SELECT P.partner
    , COUNT(DISTINCT P.post) AS nb_post
    , COUNT(DISTINCT P.postvariation) AS nb_postvariation
    , COUNT(DISTINCT P.postvariation) / COUNT(DISTINCT P.post) AS avg_postvariation
FROM posts P
GROUP BY P.partner
ORDER BY P.id DESC;

这是同一个查询,当天有一个额外的GROUP BY条款:

SELECT P.partner
    , DATE_FORMAT(P.datefield, '%Y-%m-%d') AS pivot_date
    , COUNT(DISTINCT P.post) AS nb_post
    , COUNT(DISTINCT P.postvariation) AS nb_postvariation
    , COUNT(DISTINCT P.postvariation) / COUNT(DISTINCT P.post) AS avg_postvariation
FROM posts P
GROUP BY P.partner, DATE_FORMAT(P.datefield, '%Y-%m-%d')
ORDER BY P.id DESC;

希望这会对你有所帮助。

答案 1 :(得分:1)

你需要使用除法来找到平均值。

<强>查询

SELECT partner, post, postvariation, (postvariation/post) as result 
FROM 
(
   SELECT partner, 
   COUNT(DISTINCT post) as post, 
   COUNT(DISTINCT postvariation) as postvariation
   FROM posts 
   GROUP BY partner 
   ORDER BY id DESC
) AS new_table

答案 2 :(得分:-1)

您可以尝试以下查询:

<强>查询

SELECT COUNT(postvariations), partner, post 
FROM posts 
GROUP BY partner;