2015-01-22 3 views
0

Я пытался сделать сложный запрос с этими таблицами:Выбрать и ВЫБРАСЫВАЙТЕ по столбцам

обслуживание:

id_service    description     cost 
    1     service 1      20 
    2     service 2      30 
    3     service 3      25 

истории:

id_history    status    id_service  
    1      0      1 
    2      1      1 
    3      2      1 
    4      3      1 
    5      0      2 
    6      4      1 
    7      1      2 
    8      2      2 
    9      0      3 
    10      1      3 
    11      3      2 

мне нужно знать, какие услуги не являются завершенными (статус! = 4) и группа за последнее обновление. Может быть, как это:

id_history    status   id_service   description 
    11     3     2    service 2 
    8      2     2    service 2 
    7      1     2    service 2 
    5      0     2    service 2 
    10     1     3    service 3 
    9      0     3    service 3 

Это мой текущий запрос:

SELECT a.*, b.descripcion 
FROM history a 
    JOIN service b ON a.id_service = b.id_service 
WHERE a.status != 4 

GROUP BY a.id_service  

ORDER BY a.id_history DESC 

Который только возвращает один ряд на id_service:

ID_HISTORY STATUS ID_SERVICE DESCRIPTION 
    9   0   3  service 3 
    5   0   2  service 2 
    1   0   1  service 1 
+0

я думаю вы хотите 'ORDER BY a.id_service, a.id_history DESC' и избавиться от' GROUP BY' –

ответ

0

вы можете использовать not exists ликвидировать службу со статусом 4

select h.id_history, h.status, h.id_service, s.description 
from 
service s 
join history h 
on h.id_service = s.id_service 
where not exists (select 1 from history h2 
        where h.id_service = h2.id_service 
        and h2.status = 4 
       ) 
order by h.id_history desc, h.id_service desc 

если вы хотите, последний статус для каждого сервиса, то вы можете использовать group by в подзапроса

select h.id_history, h.status, h.id_service, s.description 
from 
service s 
join (
select max(status) as status, id_service 
from history 
group by id_service 
)t 
on s.id_service =t.id_service 
and t.status !=4 
join history h 
on h.status = t.status 
and h.id_service = t.id_service 
order by h.id_history desc 
+0

Perfect! Спасибо. –

0

Я думаю, что вы не должны использовать «Группировать по» что-то вроде этого:

SELECT a.*, b.descripcion 
FROM history a 
    JOIN service b ON a.id_service = b.id_service 
WHERE a.status != 4 
ORDER BY a.id_history DESC 
Смежные вопросы