[英]Select sum where clause SQL
我有以下代碼,它可以工作,但我試圖為每個Banksphere.servicio_id列分隔SUM,這個代碼SUM只有一個servicio_id ...我有點迷失,有人可以幫幫我嗎?
正如你所看到的,每個WHERE子句都是完全相同的但是Banksphere.peticion_id是唯一一個改變的...所以也許有一些更好的方法來過濾一下常用的子句並且只留下peticion_id用於OK和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
我想你想要這樣的東西:
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
其他變量,但您只在問題中提及服務。
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
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', ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.