-1

I have SQL Table with following columns:

| Key | Created_at | Acc_id |

SQL is running in ONLY_FULL_GROUP_BY mode.

Im' trying to get, for each Acc_id, the Key that has smallest Created_at. Naturally, I would write something like

SELECT Key
       , MIN(Created_at)
       , Acc_id 
From MyTable 
GROUP BY Acc_id

But query fails, because I have ONLY_FULL_GROUP_BY and it does not know which Key to choose from the groups. I want the one corresponding to MIN(Created_at) (the one from same row), but how do I tell it?

Thanks.

VBoka
  • 8,995
  • 3
  • 16
  • 24
Zhani Baramidze
  • 1,407
  • 1
  • 13
  • 32

2 Answers2

0

Don't use group by. Use filtering. here is an example:

select t.*
from mytable t
where t.created_at = (select min(t2.created_at)
                      from mytable t2
                      where t2.acc_id = t.acc_id
                     );

This query will have optimal performance with an index on mytable(acc_id, created_at).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

With NOT EXISTS:

SELECT t.*
FROM MyTable t
WHERE NOT EXISTS (
  SELECT 1 FROM MyTable m
  WHERE m.Acc_id = t.Acc_id AND m.Created_at < t.Created_at
)
forpas
  • 160,666
  • 10
  • 38
  • 76