计算所有值和按计数分组

时间:2015-06-11 10:14:57

标签: mysql sql

我有这个查询

SELECT poll_numbers.number_title as totale_stemmen,  
       count(poll_stemmen.number_id) as stem 
FROM poll_stemmen
LEFT JOIN poll_numbers on number_id = poll_numbers.id
group by poll_stemmen.number_id

输出如下:

totale_stemmen stem    
name             1    
another          1

但是我如何计算干的总数?在这个结果中它将是2。

这是表格布局:

poll_stemmen    
number_id, id

poll_numbers
id, number_title

示例数据:

id, number_id
1   2
2   8
3   8
4   8

id, number_title
2   title_1
8   title_2

expected output:
number_title, count_number, total_number
title_1       1             4
title_2       3             4

4 个答案:

答案 0 :(得分:1)

在大多数数据库中,您只需使用窗口函数。但是,MySQL不支持这一点。

一种方法是在from子句或select中使用子查询:

SELECT n.number_title, count(s.number_id) as stem,
       x.total_number
FROM poll_stemmen s LEFT JOIN
     poll_numbers n
     on s.number_id = n.id CROSS JOIN
     (SELECT count(*) as total_number FROM poll_stemmen) x
group by s.number_id;

将查询放入from子句的一个好处是,您知道它只会被执行一次。

答案 1 :(得分:0)

试试这个

SELECT PN.`number_title`, count(PS.numberid)  
FROM `poll_stemmen` PS 
LEFT JOIN `poll_numbers` PN on PS.`numberid`=PN.`id` 
GROUP BY(PS.`numberid`)

如果您提供表结构将会很有帮助,因为此查询将计算相同标题的总词干

答案 2 :(得分:0)

您可以使用您的查询来获取number_id的计数,并使用子查询来获取总计数:

SELECT number_title, COUNT(*) AS count_number,
       (SELECT COUNT(*)
        FROM poll_stemmen
        WHERE number_id IN (SELECT id FROM poll_numbers)) AS total_number
FROM poll_numbers AS pn
LEFT JOIN poll_stemmen AS ps ON ps.number_id = pn.id
GROUP BY ps.number_id 

Demo here

答案 3 :(得分:0)

试试这个

SELECT p.number_title as number_title,
        count(p.number_id) as count_number,
        (select count(p1.id) FROM `poll_numbers` p1) as total_number  
FROM `poll_numbers` p group by number_title