Consulta de MS Access (solo dos tablas)

Tengo dos mesas:

**T1**
ID |Transaction| amount |
1  |trans1     | 97     |
1  |trans2     | 22     |
2  |trans7     | 98     |


**T2** 
ID |description|spec|
1  |Item 1     |text|
2  |Item 2     |zip |

Note: ID columns in both tables are THE SAME. However, ID in table T1 is not unique.

I need query to retrieve data from tables but only row with highest amount (table T1). Example result:

ID|description|spec|transaction|amount|
1 |item1      |text| trans1    |  97  | 
2 |item2      |zip | trans7    |  98  | 

Por favor, ayuda!

Gracias por su atención.

preguntado el 12 de septiembre de 13 a las 03:09

Your example result isn't right, is it? It shows both records have ID = 1. -

ye also it shows a mix row from T1, i.e. trans2,97 -

Oh sorry about that guys; 2AM here ... Appreciate your attention to details... -

2 Respuestas

You should use this query to get one row for each ID in the T2

SELECT ID, MAX(AMOUNT) AS AMT FROM T1 GROUP BY ID

Then join the first table into it and select all that you need. So it would look like something like this:

SELECT T2.ID,
  description,
  spec,
  transaction ,
  AMT
FROM T2
JOIN
  (SELECT ID, MAX(AMOUNT) AS AMT FROM T1 GROUP BY ID
  ) T3
ON T3.ID=T2.ID;

Note: I used Oracle, in your db you might need to modify the query in order to resolve keyword conflicts.

Respondido el 12 de Septiembre de 13 a las 03:09

It doesn't work; can't find a field transaction. I see how you get all columns but really how to get transaction or any other columns from T1 that I haven't included in my example. Any idea Ali? Thanks! - virrion

Since the field transaction doesn't appear in T2 Or T3, you'll need to modify this further. - Nick.McDermaid

If you want to get more columns on the T1 you should add them to the first sql statement above. i.e. SELECT ID, MAX(AMOUNT) AS AMT, column2, column3, ..... FROM T1 GROUP BY ID - Ali

Prueba la siguiente consulta:

SELECT ID, description, spec, `transaction` , amt
FROM T2
JOIN
  (SELECT ID, `transaction`, MAX(amount) AS amt FROM T1 GROUP BY ID) AS T3
ON T3.ID=T2.ID

watch out, because the word transaction may be a reserved keyword. You could always enclose in tick marks (like above)

Respondido el 12 de Septiembre de 13 a las 03:09

This doesn't seems to be correct. This query would throw an error: SELECT ID, MAX(amount) as amt FROM T1 - Ali

Yes, okay, added a GROUP BY cláusula. - sabléfoste

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.