I have a table like this:
Field1 | Field2 | Field3
1 | 1 | 22
1 | 2 | 10
2 | 5 | 40
2 | 2 | 55
I want to group by Field1, and then take the values from the rest of the row with the minimal Field2, eg:
Field1 | Field2 | Field3
1 | 1 | 22
2 | 2 | 55
Note that this is not the same as selecting the minimum of each row, which would give:
Field1 | Field2 | Field3
1 | 1 | 10
2 | 2 | 40
Which with my data would be a meaningless result.
Does anyone have a general (ie. multi database) solution to this? I'm sure it must be a solved problem!
I could really do with a solution that works in both sqlite and ms-access, and sql server would be a bonus.
In Power Query, you can group values in various rows into a single value by grouping the rows according to the values in one or more columns. You can choose from two types of grouping operations: Aggregate a column by using an aggregate function.
1 Select Group by on the Home tab. 2 Select the Advanced option, so you can select multiple columns to group by. 3 Select the Country and Sales Channel columns. 4 In the New columns section, create a new column where the name is Total units, the aggregate operation is Sum, and the column used is Units. 5 Hit OK
Simpliy get (WHERE) one ( MIN (record_date)) row from the current group: SELECT * FROM t t1 WHERE record_date = ( select MIN (record_date) from t t2 where t2.group_id = t1.group_id) then (AND) pick only one from the 2+ min record_date rows, within the given group_id. E.g. pick the one with the min unique key:
In Power Query, you can group values in various rows into a single value by grouping the rows according to the values in one or more columns. You can choose from two types of grouping operations: Aggregate a column by using an aggregate function. Perform a row operation.
You'll have to execute this with subqueries.
Select * from
yourtable t
inner join
( Select field1, min(field2) as minField2
from yourtable
group by field1
) xx
on t.field1 = xx.field1 and t.field2 = xx.minfield2
Now, if you have multiple rows for a minimal field2 value, then you'll have dupes...If you don't want that (i.e. you want the minimal value of field3 for every minimal value of field2) in that case, you'd need another sub query:
Select outert.field1, outert.field2, outert.field3
from yourtable outert
inner join
(
Select t.field1, xx.minfield2, min(field3) as minfield3 from
yourtable t
inner join
( Select field1, min(field2) as minField2
from yourtable
group by field1
) xx
on t.field1 = xx.field1 and t.field2 = xx.minfield2
group by t.field1, xx.minfield2
) outerx
on outerx.field1 = outert.field1
and outerx.field2 = outert.minfield2
and outerx.field3 = outert.minfield3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With