SQL查询中分组的COUNT的总和


69

我有一个包含2个字段的表格:

身份证名
--------
1个Alpha
2 Beta
3 Beta
4 Beta
5查理
6查理

我想按名称将其分组,并带有“计数”和一行“ SUM”

名字计数
------- -----
阿尔法1
Beta 3
查理2
总和6

如何编写查询以在表下方添加SUM行?


3
如果您需要选择本身中的总和来进行计算,请使用子选择:SELECT Name, COUNT(*) AS amount, COUNT(*)/total.total * 100 AS percentage, total.total FROM temp, ( SELECT COUNT(*) AS total FROM temp ) AS total GROUP BY Name 请参见SQLfiddle
yunzen 2014年

请注意以下答案-如果没有ORDER BY,查询结果将无法保证顺序。
philipxy

Answers:


72
SELECT name, COUNT(name) AS count
FROM table
GROUP BY name

UNION ALL

SELECT 'SUM' name, COUNT(name)
FROM table

输出:

name                                               count
-------------------------------------------------- -----------
alpha                                              1
beta                                               3
Charlie                                            2
SUM                                                6

有效答案。请使用汇总查看@Adriann的答案。 stackoverflow.com/a/12927333/2012977
Osa E

什么Union all啊 编辑:好的,我因为缩进而感到困惑。这是两个选择器的联合:)
mcoenca


13

没有指定您正在使用哪个rdbms

看看这个演示

SQL小提琴演示

SELECT Name, COUNT(1) as Cnt
FROM Table1
GROUP BY Name
UNION ALL
SELECT 'SUM' Name, COUNT(1)
FROM Table1

就是说,我建议您将总数添加到您的表示层而不是数据库中。

这是使用ROLLUP汇总数据的SQL SERVER版本的更多内容

SQL小提琴演示

SELECT CASE WHEN (GROUPING(NAME) = 1) THEN 'SUM'
            ELSE ISNULL(NAME, 'UNKNOWN')
       END Name, 
      COUNT(1) as Cnt
FROM Table1
GROUP BY NAME
WITH ROLLUP

第二个选择不应该是总和,而不是计数吗?
格雷格(Greg)2012年

@Greg,如果您要重新引用顶部的语句(可能使用WITH CTE语句(Sql Server)),则应该是总和。
Adriaan Stander 2012年

1
感谢您指出汇总。您的答案应该是被接受的答案。我们有巨大的桌子,讨厌两次打桌子。
Osa E

8

尝试这个:

SELECT  ISNULL(Name,'SUM'), count(*) as Count
FROM table_name
Group By Name
WITH ROLLUP


2

您可以使用联合来联接行。

select Name, count(*) as Count from yourTable group by Name
union all
select "SUM" as Name, count(*) as Count from yourTable

2

对于Sql Server,您可以尝试这一方法。

SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE

2

这里的所有解决方案都很棒,但不一定可以针对旧的mysql服务器实现(至少就我而言)。因此您可以使用子查询(我认为它不那么复杂)。

 select sum(t1.cnt) from 
        (SELECT column, COUNT(column) as cnt
            FROM
            table 
            GROUP BY 
            column
            HAVING 
            COUNT(column) > 1) as t1 ;

这对我来说很有意义
卢凯耀(KY Lu)

2

我解释这个问题的方式是需要每组答案的小计值。使用以下方法,小计非常容易PARTITION

SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]

这是我完整的SQL调用的样子:

SELECT MAX(GroupName) [name], MAX(AUX2)[type],  
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
    FROM [MyView]
  WHERE Active=1 AND Type='APP' AND Completed=1
    AND [Date] BETWEEN '01/01/2014' AND GETDATE()
    AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
  GROUP BY AUX2, GroupId

从中返回的数据如下所示:

name    type    count   total
Training Group 2    Cancelation 1   52
Training Group 2    Completed   41  52
Training Group 2    No Show 6   52
Training Group 2    Rescheduled 4   52
Training Group 3    NULL        4   10535
Training Group 3    Cancelation 857 10535
Training Group 3    Completed   7923    10535
Training Group 3    No Show 292 10535
Training Group 3    Rescheduled 1459    10535
Training Group 4    Cancelation 2   27
Training Group 4    Completed   24  27
Training Group 4    Rescheduled 1   27

1
  with cttmp
  as
  (
  select Col_Name, count(*) as ctn from tab_name group by Col_Name having count(Col_Name)>1
  )
  select sum(ctn) from c


0

您可以按名称尝试分组,并计算该组中的ID。

SELECT name, count(id) as COUNT FROM table group by name

我想您会错过'SUM'

0

用作

select Name, count(Name) as Count from YourTable
group by Name
union 
Select 'SUM' , COUNT(Name) from YourTable

我选择UNION ALL而不是UNION来将“ SUM”行放在底部(根据@VishalSuthar的上述回答)
nametal

我认为您误解了UNION和UNION ALL那UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.就是我使用UNION
Usman,2012年

感谢您的回调,但在这种情况下,我必须把“SUM”的底线,其可以通过使用UNION ALL来完成
nametal

您是否尝试过使用UNION?正如我尝试过的那样,必须将'SUM'放在底部,但就性能而言,UNION ALL在您的方案中效果很好,因为UNION的性能要差得多,因为它必须扫描结果对于重复..
奥斯曼

我已经在较大的数据库中尝试过,并将“ SUM”放置在表的中间(并非总是在底部)。无论如何,我明白了UNION ALL和UNION之间的区别,谢谢
nametal 2012年

0

我正在使用SQL Server,以下应该适用于您:

通过名称联合从表1组中选择cast(名称为varchar(16))作为'名称',将count(name)作为'Count'通过名称联合全部选择Table1中的'Sum:',count(name)


0

having count(*) > 1也需要。因此,我在参考了上述一些查询后编写了自己的查询

句法:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;

例:

select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;

-1

查询后,运行下面的命令以获取总行数

select @@ROWCOUNT

1
他想知道例如CHARLIE的数目,而不是NAMES的数目。
Magier '17

-5

从(Tab_name组中选择count(Col_name)作为具有count(*)> 1的Col_name从Tab_name组中选择s)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.