[英]SQL count rows with same value in column and group by id?
我有一张这样的桌子:
id | value
1 | 1
2 | 1
3 | 2
4 | 3
我想知道是否可以计算具有相同值的行并按 id 对它们进行分组,但是如果我按 id 而不是按值对它们进行分组,则每次代码都会返回计数 1
想要的输出:
id | count
1 | 2(there are 2 rows with value 1)
2 | 2
3 | 1
4 | 1
在没有窗口函数的 MySQL 版本中,您可以通过对value
进行自连接来实现您想要的结果,计算第二个表中的值的数量:
SELECT t1.id, COUNT(t2.value) AS cnt
FROM table1 t1
JOIN table1 t2 ON t2.value = t1.value
GROUP BY t1.id
输出:
id cnt
1 2
2 2
3 1
4 1
在 MySQL 8+ 中,您将使用窗口函数:
select t.*, count(*) over (partition by value) as cnt
from t;
我认为你想要的没有意义。 正如我所看到的,id 列是一个自动增量整数,因此它不能按 id 分组并且不能分组多个值。 如果您想要的是一个将数字保存在一列中并且该数字出现在另一列中的次数的表,则必须执行以下操作:
SELECT value AS id, COUNT(value) AS count FROM table GROUP BY value ORDER BY value ASC;
如果你真的想要你在问题中指定的结果,我建议这样做:
declare @Orig table (ID int, val int)
insert into @Orig values (1, 1),
(2, 1),
(3, 2),
(4, 3)
--select * from @Orig --show example table
declare @Stat table (val int, cnt int)
insert into @Stat
select val as ID, count(val) as count from @Orig group by val order by val asc
--select * from @Stat --L. Ribo's query results from group/order query
select o.ID, s.cnt from @Orig o
inner join @Stat s on o.val = s.val
结果:
ID cnt
1 2
2 2
3 1
4 1
将统计表与原始表联接。 当然,在没有临时表的情况下,可能有一些优雅的方法可以做到这一点,但是通过逐步解决它对我来说更容易解决和理解。 这是在 SQL Server 中完成的。 其他风格的 SQL(如 MySQL)中的临时表具有不同的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.