问题
This may be an extremely easy question but I can't get my head around how to solve it in MS Access. It has probably been answered before but I haven't been able to find it.
I have a table with 3 columns: col1 is an object ID, col2 and col3 are measurements. I've built a query so that for each object we get the corresponding minimum value in col2. This works OK with a simple group-by query. The problem is when I try to pull col3 (associated with the row where minimum value was found), it will no longer group-by properly.
I've been playing with the group-by clause and tried to divide into several queries but so far no luck.
Here's an example of what I have (left) and would like to get (right):
col1 col2 col3 ---> col1 minC2 col3 ---- ---- ---- ---- ---- ---- 1 0 1.8 1 0 1.8 1 1 1.4 2 2 2.5 2 4 1.1 3 1 7.6 2 6 4.7 2 2 2.5 3 4 3.3 3 1 7.6
I hope this makes sense. Any help/MS Access SQL syntax is appreciated... Thanks!
回答1:
Assuming that the second line of what you like to get is [2 2 2.5], this is what you're looking for:
select a.col1, a.colm, m.col3
from
(
select col1, min(col2) as colm
from test
group by col1
) as a
inner join test m on a.col1 = m.col1 and a.colm = m.col2
回答2:
You can use a subquery:
select t.col1, tt.col2 , tt.col3
from (
SELECT col1, Min(col2) AS mcol2
FROM Tmp
group by col1) t, tmp tt
where t.col1 = tt.col1 and t.mcol2 = tt.col2
来源:https://stackoverflow.com/questions/11063408/ms-access-sql-aggregating-on-min-value-but-retrieving-other-fields