简体   繁体   中英

SQL query for grouping by 2 columns and taking the first occurrence of 3rd column

I am not great at SQL queries so I thought I'd ask here. I have a table my_table :

NOTE : Consider all the columns as strings . I just represent them as numbers here for a better understanding.

A B C
-----
1 2 3
2 2 3
2 5 6
3 5 6

I want the result to be-

A B C
-----
1 2 3
2 5 6

So basically, dropping duplicate pairs for B, C , and taking the first occurrence of A for that pair of B, C .

first, you'd better post some of the something you tried here.

In mysql 8.0 you can use row_number() over (partition by B, C order by A) to slove this question.

 CREATE TABLE Table1 (`A` int, `B` int, `C` int); INSERT INTO Table1 (`A`, `B`, `C`) VALUES (1, 2, 3), (2, 2, 3), (2, 5, 6), (3, 5, 6);
 select `A`, `B`, `C` from ( select *,row_number() over (partition by `B`, `C` order by `A`) rnk from Table1 ) T where rnk = 1;
 A | B | C -: |  -: |  -: 1 |  2 |  3 2 |  5 |  6 

db<>fiddle here

if mysql < 8.0 you can follow this answerROW_NUMBER() in MySQL


Update:

if like @forpas says: taking the first occurrence of A for that pair of B, C is not solved by order by A.

You have to sort the rownum first:

 CREATE TABLE Table1 (`A` int, `B` int, `C` int); INSERT INTO Table1 (`A`, `B`, `C`) VALUES (2, 2, 3), (1, 2, 3), (2, 5, 6), (3, 5, 6);
 SET @rownum:=0; select `A`, `B`, `C` from ( select *,row_number() over (partition by `B`, `C` order by rownum) rnk from ( select *,@rownum:=@rownum+1 AS rownum from Table1 ) T ) T where rnk = 1;
 ✓ A |  B | C -: |  -: |  -: 2 |  2 |  3 2 |  5 |  6 

db<>fiddle here

You seem to want aggregation:

select min(a) as a, b, c
from t
group by b, c;

I assumes "first" means the minimum value of a . SQL tables represent unordered sets, so that seems like the most sensible interpretation.

Seems you need to consider the minimum of the column A and grouping by B and C :

select min(cast(A as unsigned)) as A, cast(B as unsigned) as B, cast(C as unsigned) as C
  from my_table
 group by B , C 

cast(<column> as unsigned) conversion is used to make them numeric.

Demo

select min(A) as A,B,C 
from Table1
group by B,C

As, you requested this will get the minimum value of A for combinations of B and C.

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