One of my mates asked me a question related to building of sql query. She was asked that question on the interview for one IT company and had a difficulties with finding a solution.
Task:
Solution:
The question looks simple but there is a little trick in solution.
After solving this exercise I was interested in this question and looked for possibly more optimal solutions. There is a lot of information about getting the max in group on this page.
Task:
There are 2 tables in database. One table containes 2 fields: ID (int, primary key) and client account number (int). The other table contains 4 fields: ID (int), date (Date), the counter (int), the client account number (key, linked to first table).
Result of query should show client account number, the counter's value for latest date from table 2 for this account, that latest date.
Solution:
SELECT AN.AccountNumber, C.Date, C.Counter FROM AccountNumbers AS AN INNER JOIN (SELECT Counters.AccountNumber, Counters.Date, Counters.Counter, MAX(Counters.Date) OVER(PARTITION BY Counters.AccountNumber) AS "MaxDate" FROM Counters) AS C ON AN.ID = C.AccountNumber WHERE C.Date = C.MaxDate
The question looks simple but there is a little trick in solution.
After solving this exercise I was interested in this question and looked for possibly more optimal solutions. There is a lot of information about getting the max in group on this page.
Комментариев нет:
Отправить комментарий