简体   繁体   中英

SQL count rows with same value in column and group by id?

i have a table like this:

id  | value
1   |   1
2   |   1
3   |   2
4   |   3

i wonder if its possible to count the rows with same value and group them by id , but every time the code will return count 1 if i group them by id and not by value

wanted output:

id  | count
1   |   2(there are 2 rows with value 1)
2   |   2
3   |   1
4   |   1

You need to count the value of the column value for each id:

select 
  t.id,
  (select count(*) from tablename where value = t.value) count
from tablename t 

See the demo
or:

select t.id, g.count
from tablename t inner join (
  select value, count(value) count
  from tablename 
  group by value
) g on g.value = t.value

See the demo

In MySQL versions without window functions, you can achieve the results you want with a self join on value , counting the number of values in the second table:

SELECT t1.id, COUNT(t2.value) AS cnt
FROM table1 t1
JOIN table1 t2 ON t2.value = t1.value
GROUP BY t1.id

Output:

id  cnt
1   2
2   2
3   1
4   1

Demo on dbfiddle

In MySQL 8+, you would use window functions:

select t.*, count(*) over (partition by value) as cnt
from t;

I think what you want doesn't make sense. As I can see, id column is an auto incremental integer, so it can't be grouped by id and have more than one value grouped. If what you want is a table that saves the number in one column and the number of times that this number appears in another column, you will have to execute this:

SELECT value AS id, COUNT(value) AS count FROM table GROUP BY value ORDER BY value ASC;

If you really want the results you specified in your question, I suggest this:

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

Results:

ID cnt
1   2
2   2
3   1
4   1

Join the statistics table with the original table. Of course there's probably some elegant way to do this without temporary tables, but it's easier for me to solve and understand by taking it in steps. This was done in SQL Server. Temporary tables in other flavors of SQL (like MySQL) have a different syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM