A
A
Alexander2018-10-06 13:24:16
SQL
Alexander, 2018-10-06 13:24:16

How to arrange a selection from the database from each group of values ​​according to certain parameters?

There is a plate
Id | name | date | Other
------------------------------------------------ ---------------
1 | A | 2018-09-20 16:15:00 | 555
1 | A | 2018-09-22 15:25:00 | 666
1 | A | 2018-09-26 19:45:00 | 7772
| b | 2018-08-15 12:22:00 | 555
2 | b | 2018-09-19 14:01:00 | 666
3 | c | 2018-09-26 09:39:00 | 555
It is necessary to select from it the rows where the value by date is the latest value AND the row where Other = 555.
So far I have learned to select the last row like this:
select * from
(select * from table Date desc) as x
group by Id
The result of the selection is:
1 | A | 2018-09-26 19:45:00 | 7772
| b | 2018-09-19 14:01:00 | 666
3 | c | 2018-09-26 09:39:00 | 555
QUESTION
How can I make the line with the value Other = 555 appear after the line with the highest value in the group?
Need to get:
1 | A | 2018-09-26 19:45:00 | 7771
| A | 2018-09-20 16:15:00 | 555
2 | b | 2018-09-19 14:01:00 | 666
2 | b | 2018-08-15 12:22:00 | 555
3 | c | 2018-09-26 09:39:00 | 555
^^^^^^^^^^^^
^^^^^^^^^
^^^^^^
^^^
PS. Is it possible to use a sql query to make it so that the row where the date in the group is the most recent is displayed, BUT the date column in this row would be displayed from the row where Other is 555? those. on the existing example, the conclusion is
1 | A | 2018-09-20 16:15:00 | 7772
| b | 2018-08-15 12:22:00 | 666
3 | c | 2018-09-26 09:39:00 | 555

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nozzy, 2018-10-06
@nozzy

Didn't check

select
t2.Id,
t2.Name,
t3.Date,
t2.Other
from
(
select
    t1.Id,
    t1.Name,
    t1.Date,
    t1.Other
    from your_table t1
    where not exists (
        select 1 
        from your_table 
        where Id = t1.Id
        and Date > t1.Date
    )
) t2 join (
      select 
      Id,
      Name,
      Date as Date,
      Other
      from test4 
      where Other = 555	
    ) t3 on t3.Id = t2.Id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question