简体   繁体   中英

Sql to get a specific result from table rows

I use mysql and I need a sql to get a table result with some rows.

I'd better to show with a sample

tableA

id, autfis_id, name, col1, col2 ...... coln
1,1,a, col1_content ... coln_content
2,1,a, col1_content ... coln_content
3,2,c, col1_content ... coln_content
4,1,a, col1_content ... coln_content
5,2,c, col1_content ... coln_content
6,3,d, col1_content ... coln_content

Expected Result

id,autfis_id,count(rows with same autfis_id), name, col1 ..... coln
1,1,3,a, col1_content ... coln_content
3,2,2,c, col1_content ... coln_content
6,3,1,d, col1_content ... coln_content

where id is the first id found from rows containing the same 'autfis_id'

You can include id but is wrong because why do you get "the first id" instead another one?

SELECT 
MIN(id) as id,
autfis_id,
COUNT(*) as sameTotal,
name
FROM
yourtable
GROUP BY autfis_id, name

MySQL's Windows Functions is what you need. Try this:

select distinct first_value(id) over (partition by autfis_id order by id), 
       autfis_id, 
       count(1) over (partition by autfis_id),
       name 
  from tablea;

Tested it with this script:

create database test;
use test;
create table tablea (id int, autfis_id int, name varchar(20));
insert into tablea values (1,1,'a');
insert into tablea values (2,1,'a');
insert into tablea values (3,2,'c');
insert into tablea values (4,1,'a');
insert into tablea values (5,2,'c');
insert into tablea values (6,3,'d');

Do keep in mind that if names differ, then you might get more rows than what you're expecting. But it's hard to tell when we don't know what the data structure is actually representing, and what are its expected values.

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