Я пытаюсь получить максимальное значение noteId для каждого проекта, но возвращаю заметки, которые были закреплены первыми, и не возвращаю заметки, которые не закреплены в том же проекте.
select refId as projectId, max(noteId) as noteId
from notes
where noteType='project'
and ((noteCat='critical project' and pinned=1) or noteCat='critical
project')
group by refId, pinned
order by pinned desc
Пример данных:
|---------|-----------|--------------|------------------|----------|
| noteId | projectId | noteType | noteCat | pinned |
|---------|-----------|--------------|------------------|----------|
| 306586 | 34256 | project | critical project | 1 |
|---------|-----------|--------------|------------------|----------|
| 298183 | 972 | project | critical project | 0 |
|---------|-----------|--------------|------------------|----------|
| 296114 | 32549 | project | critical project | 0 |
|---------|-----------|--------------|------------------|----------|
| 295668 | 972 | project | critical project | 0 |
|---------|-----------|--------------|------------------|----------|
| 295463 | 972 | project | critical project | 1 |
|---------|-----------|--------------|------------------|----------|
Ожидаемые результаты должны быть:
|---------------------|------------------|------------------|
| Project Id | Note Id | Pinned |
|---------------------|------------------|------------------|
| 972 | 295463 | 1 |
|---------------------|------------------|------------------|
| 34256 | 306586 | 0 |
|---------------------|------------------|------------------|
| 32549 | 296114 | 1 |
|---------------------|------------------|------------------|
Фактические результаты:
|---------------------|------------------|------------------|
| Project Id | Note Id | Pinned |
|---------------------|------------------|------------------|
| 972 | 295463 | 1 | -- Older noteId but pinned.
|---------------------|------------------|------------------|
| 34256 | 306586 | 0 |
|---------------------|------------------|------------------|
| 972 | 298183 | 0 | --This should not be returned.
|---------------------|------------------|------------------|
| 32549 | 296114 | 1 |
|---------------------|------------------|------------------|