我有以下代码,它有效,但我试图为每个Banksphere.servicio_id列分隔SUM,这个代码SUM只有一个servicio_id ...我有点迷失了,有人能帮帮我吗?
正如你所看到的,每个WHERE子句都是完全相同的但是Banksphere.peticion_id是唯一一个改变的......所以也许有一些更好的方法来过滤一下普通的子句并只留下peticion_id好的和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
使用工作代码编辑
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
答案 0 :(得分:20)
我认为你想要这些内容:
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
这有一个group by
,因此您可以获得多个“servicio_ids”,并为OK和KO添加单独的列。如果只想要servicio_id = 6,则将其添加回where
子句。并且,您可能还需要group by
中的其他变量,但您只在问题中提及服务。
答案 1 :(得分:3)
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
答案 2 :(得分:1)
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', ...)