15

I have the following code, it works but I am trying to separate SUM for each Banksphere.servicio_id column, this code SUM only one servicio_id... I'm a bit lost, can someone help me?

As you can see, every WHERE clause is exactly the same but Banksphere.peticion_id which is the only one that changes... So maybe there's some better way just to filter once the common clauses and leave only peticion_id for OK and KO?

SELECT
(SELECT
    SUM(valor)
FROM
    Banksphere
WHERE
    Banksphere.fecha = '2013-01-14'
AND
    Banksphere.servicio_id = '6'
AND
    Banksphere.entidad_id = '2'
AND
    Banksphere.peticion_id = '0') AS OK,
(SELECT
    SUM(valor)
FROM
    Banksphere
WHERE
    Banksphere.fecha = '2013-01-14'
AND
    Banksphere.servicio_id = '6'
AND
    Banksphere.entidad_id = '2'
AND
    Banksphere.peticion_id = '1') AS KO

EDIT WITH WORKING CODE

SELECT  Servicios.nombre as servicio,
        SUM(case when peticion_id = '0' then valor end) as OK,
        SUM(case when peticion_id = '1' then valor end) as KO
FROM    Banksphere
INNER JOIN
    Servicios
ON
    Banksphere.servicio_id = Servicios.id
WHERE   Banksphere.fecha = '2013-01-14'
        AND Banksphere.entidad_id = '2'
        AND Banksphere.peticion_id in ('0', '1')
group by Servicios.nombre
Robert W. Hunter
  • 2,895
  • 7
  • 35
  • 73

3 Answers3

29

I think you want something along these lines:

SELECT  banksphere.servicio_id, SUM(valor),
        SUM(case when peticion_id = '0' then valor end) as OK,
        SUM(case when peticion_id = '1' then valor end) as KO
FROM    Banksphere
WHERE   Banksphere.fecha = '2013-01-14'
        AND Banksphere.entidad_id = '2'
        AND Banksphere.peticion_id in ('0', '1', ...)
group by banksphere.servicio_id

This has a group by so you can get multiple "servicio_ids" and it adds separate columns for OK and KO. If you want only servicio_id = 6, then add that back into the where clause. And, you might want other variables in the group by as well, but you only mention service in the question.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
4
SELECT  servicio_id,
        entidad_id,
        SUM(CASE WHEN peticion_id = 0 THEN valor ELSE 0 END) OK,
        SUM(CASE WHEN peticion_id = 1 THEN valor ELSE 0 END) KO
FROM    BankSpehere
WHERE   fecha = '2013-01-14' AND 
        entidad_id = '2' AND 
        peticion_id in ('0', '1')
GROUP BY servicio_id, entidad_id
John Woo
  • 258,903
  • 69
  • 498
  • 492
2
SELECT  SUM(valor)
FROM    Banksphere
WHERE   Banksphere.fecha = '2013-01-14'
        AND Banksphere.servicio_id = '6'
        AND Banksphere.entidad_id = '2'
        AND Banksphere.peticion_id in ('0', '1', ...)
Andomar
  • 232,371
  • 49
  • 380
  • 404