Query Mysql returning differently

Asked

Viewed 43 times

0

I have the following Query:

select 
    MONTHNAME(ta2.change_time) as mes,
    MONTH(ta2.change_time) as numeroMes,
    case 
        when s2.name like '%Servidores' then cast(SUM(ta2.time_unit) as UNSIGNED) * 1.5  else cast(SUM(ta2.time_unit) as UNSIGNED)
    end as TEMPO_CORRETO
from 
    otrs.service s2,
    otrs.time_accounting ta2,
    otrs.ticket t2,
    otrs.ticket_type tt2
where
    t2.id = ta2.ticket_id and
    t2.type_id = tt2.id and
    t2.service_id = s2.id and
    ta2.change_time between '2018-04-01' and '2018-04-30' and
    t2.customer_id = 'ZSCHIMMER SCHWARZ' and
    tt2.name = 'Contrato PCH'
group by 
    t2.customer_id,
    s2.name
order by 
    numeroMes

But I’m getting the following feedback:

inserir a descrição da imagem aqui

However I would like to group these values per month, having a result like this:

inserir a descrição da imagem aqui

I’ve tried everything but I haven’t got it yet, if you have an idea.

  • first need to include mes, numeroMes in the group by, but what do you want to do with the tempo_correto? Need to use some aggregation function on it, sum, avg, etc.

1 answer

1


You can simplify that expession there of the third column (turned first, according to your requirement).

You need to group by columns that will be treated as 'totalizers''.

SELECT 
    CAST(SUM(CASE WHEN s2.name LIKE '%Servidores' THEN ta2.time_unit * 1.5 ELSE ta2.time_unit END ) AS UNSIGNED) AS TEMPO_CORRETO
    MONTHNAME(ta2.change_time) AS MES,
    MONTH(ta2.change_time) AS NUMEROMES
FROM 
    otrs.service s2,
    otrs.time_accounting ta2,
    otrs.ticket t2,
    otrs.ticket_type tt2
WHERE
    t2.id = ta2.ticket_id AND
    t2.type_id = tt2.id AND
    t2.service_id = s2.id AND
    ta2.change_time between '2018-04-01' AND '2018-04-30' AND
    t2.customer_id = 'ZSCHIMMER SCHWARZ' AND
    tt2.name = 'CONTRATO PCH'
GROUP BY 
    MONTHNAME(ta2.change_time),
    MONTH(ta2.change_time)
ORDER BY 
    NUMEROMES

Important: This consultation is not dealing with the possibility of having records of the same month in different years. See if that wouldn’t be the case for your business rule.

  • Diego just a doubt, when I put a period of '2018-02-01' until '2018-04-30', it returns me only the month of March and April since in February there are no records, it is possible that when there is no record it brings the month anyway and the value zero in place?

  • @R.Santos Possible is. But it’s a little more complicated. That question deals with precisely this. In that other has some alternative proposals too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.