我有一个包含2个字段的表格:
身份证名 -------- 1个Alpha 2 Beta 3 Beta 4 Beta 5查理 6查理
我想按名称将其分组,并带有“计数”和一行“ SUM”
名字计数 ------- ----- 阿尔法1 Beta 3 查理2 总和6
如何编写查询以在表下方添加SUM行?
Answers:
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
Union all
啊 编辑:好的,我因为缩进而感到困惑。这是两个选择器的联合:)
SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
FROM Table GROUP BY name
没有指定您正在使用哪个rdbms
看看这个演示
SELECT Name, COUNT(1) as Cnt
FROM Table1
GROUP BY Name
UNION ALL
SELECT 'SUM' Name, COUNT(1)
FROM Table1
就是说,我建议您将总数添加到您的表示层而不是数据库中。
这是使用ROLLUP汇总数据的SQL SERVER版本的更多内容
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
请按以下方式运行:
Select sum(count)
from (select Name,
count(Name) as Count
from YourTable
group by Name); -- 6
这里的所有解决方案都很棒,但不一定可以针对旧的mysql服务器实现(至少就我而言)。因此您可以使用子查询(我认为它不那么复杂)。
select sum(t1.cnt) from
(SELECT column, COUNT(column) as cnt
FROM
table
GROUP BY
column
HAVING
COUNT(column) > 1) as t1 ;
我解释这个问题的方式是需要每组答案的小计值。使用以下方法,小计非常容易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
您可以使用ROLLUP
select nvl(name, 'SUM'), count(*)
from table
group by rollup(name)
用作
select Name, count(Name) as Count from YourTable
group by Name
union
Select 'SUM' , COUNT(Name) from YourTable
UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.
就是我使用UNION
我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`;
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