Here is my table with sample data:
id|group_id|column1|column2|column3|
--------------------------------------
1 1 | 1 1 0
2 1 | 1 1 1
3 2 | 0 0 0
4 2 | 1 1 1
5 1 | 1 0 0
6 3 | 0 0 0
Expected result set: (The result should show the maximum sum (col 1 + col 2 + col 3) in each group)
id|group_id|column1|column2|column3|
--------------------------------------
2 1 | 1 1 1
4 2 | 1 1 1
6 3 | 0 0 0
Actual result set: (select *, max(m.column1 + m.column2 + m.column3) as total from my_table m group by m.group_id) which is wrong
id|group_id|column1|column2|column3|total|
------------------------------------------
1 1 | 1 1 0 3
3 2 | 0 0 0 3
6 3 | 0 0 0 0
I'm quite new to SQL, it seems like the query selecting the first id in each group.
what is the best way to get expected result?
Looks like you are trying to get the rows that yield highest sum of 3 columns in each group:
select a.*
from my_table a
join (
select group_id, max(column1 + column2 + column3) summation
from my_table
group by group_id) b on a.group_id = b.group_id and a.column1 + a.column2 + a.column3 = b.summation;
You can do get your desired result ie with a subselect:
First step:
SELECT
MAX(m1.column1 + m1.column2 + m1.column3)
FROM
my_table m1
GROUP BY
m1.group_id
will get you the maximum total per group_id.
Because values in non aggregated columns are indetermined, if this columns contains different values for a group, you can't simply aggregate as you've done, but a subselect using the query from first step will do it:
Complete query
SELECT
*,
m.column1 + m.column2 + m.column3 as total
FROM
my_table m
WHERE
m.column1 + m.column2 + m.column3 = (
SELECT
MAX(m1.column1 + m1.column2 + m1.column3)
FROM
my_table m1
WHERE
m.group_id = m1.group_id
GROUP BY
m1.group_id
);
You didn't specified exactly which values for column1, column2 and column3 must be returned.
select m.*,n.* from
m,
(select
group_id as n_group_id,
max(column1+column2+column3) as n_total
from m group by group_id) as n
where m.group_id=n_group_id and (column1+column2+column3)=n_total
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.