MSSQL Loop - How to - sql-server

I need your help on this please:
I have one table in which ID_Erreur_CallBack could be NULL, 0, 1, 2, 3, 4, 5 or 6.
If I execute:
SELECT ID_SkillGroup AS Competence
,ID_Erreur_CallBack
,count(*) AS Nombre_de_Ocurrences
,CASE ID_Erreur_CallBack
WHEN '0'
THEN 'Abandon pendant l’exécution du script (le client a raccroché)'
WHEN '1'
THEN 'Ligne occupée'
WHEN '2'
THEN 'Le client n’a pas confirmé en appuyant sur étoile'
WHEN '3'
THEN 'Le client n’a pas décroché'
WHEN '4'
THEN 'Le numéro de téléphone du client est invalide'
WHEN '5'
THEN 'Problemes de ressources lors de l’appel'
WHEN '6'
THEN 'Echec de l’appel'
ELSE 'Appel réussi'
END AS Description_Erreur
FROM dbo.TB_WCB_USER
WHERE Date_Heure_Insert BETWEEN '01/11/2015'
AND '01/12/2015'
AND TYPE = 'WCB'
GROUP BY ID_SkillGroup
,ID_Erreur_CallBack
ORDER BY ID_SkillGroup
,ID_Erreur_CallBack ASC
And I get for example:
Result
I want to make a SELECT statement where I can vary ID_Erreur_CallBack from 0 to 6 and NULL even if Nombre_de_Ocurrences is 0 (or NULL). Something like:
Result I wish
Thank you!

Instead of using a CASE You create a table with your errors description, that way is easy to mantain if you want add or update text, dont need change code.
like errors
error_id error_text
1 err1
2 err2
3 err3
....
100 'Appel réussi'
THEN use LEFT JOIN
select ID_SkillGroup as Competence,
E.error_id as ID_Erreur_CallBack,
E.error_text as Description_Erreur,
count(*) as Nombre_de_Ocurrences
FROM errors E
LEFT JOIN TB_WCB_USER W
ON E.error_id = ID_Erreur_CallBack
I see you have an ELSE on your CASE
You can do something like this
LEFT JOIN TB_WCB_USER W
ON E.error_id = CASE ID_Erreur_CallBack
WHEN > 99 then 100 -- 'Appel réussi'
ELSE ID_Erreur_CallBack
END

Thank for the answer Juan Carlos.
I finally used CROSS JOIN
/*Creation de table temporaire et remplisage avec NULL*/
WITH T1 AS (
SELECT n = 0
UNION ALL
SELECT n + 1 FROM T1 WHERE n < 6
)
SELECT n INTO #Temp_Cesar FROM T1
INSERT INTO #Temp_Cesar (n) VALUES (NULL)
SELECT t1.ID_SkillGroup as Competence,t2.n as ID_Erreur_CallBack
INTO #Temp_Cesar1
FROM dbo.TB_SKILLGROUP t1
CROSS JOIN #Temp_Cesar t2
ORDER BY t1.ID_SkillGroup
ALTER TABLE #Temp_Cesar1 ADD Nombre_de_Ocurrences INT NULL, Description_Erreur VARCHAR(30) NULL;
select Competence,isnull(ID_Erreur_CallBack,99) as ID_Erreur_CallBack,isnull(Nombre_de_Ocurrences,0) as Nombre_de_Ocurrences,
Case ID_Erreur_CallBack
WHEN '0' THEN 'Abandon pendant l’exécution du script (le client a raccroché)'
WHEN '1' THEN 'Ligne occupée'
WHEN '2' THEN 'Le client n’a pas confirmé en appuyant sur étoile'
WHEN '3' THEN 'Le client n’a pas décroché'
WHEN '4' THEN 'Le numéro de téléphone du client est invalide'
WHEN '5' THEN 'Problemes de ressources lors de l’appel'
WHEN '6' THEN 'Echec de l’appel'
ELSE 'Appel réussi'
END AS Description_Erreur
into #Temp_Cesar11 from #Temp_Cesar1

Related

Write query with subquery in CodeIgniter4 Query Builder?

I have the following query which has an issue with Query Builder.
SELECT IIF(ISNULL(MAX(CODCLIENTE), 0) + 1 = 1,
(SELECT VALOR + 1
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MINIM'
AND USUARIO = '1'),
ISNULL(MAX(CODCLIENTE), 0) + 1)
FROM CLIENTES
WHERE CODCLIENTE >= (SELECT VALOR
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MINIM'
AND USUARIO = '1')
AND CODCLIENTE <= (SELECT VALOR
FROM PARAMETROS
WHERE LTRIM(RTRIM(SUBCLAVE)) = 'MAXIM'
AND USUARIO = '1');
Is there any way to do it with Query Builder? I'm currently using this method.

Join two similar queries made to the same table in PostgreSQL

Good evening, I have generated two queries to a PostgreSQL database, which are the following:
SELECT tarea, count(estado) AS "TotalCompletos" from tabla WHERE estado = 'Completo' GROUP BY tarea;
Query_1_result.png
SELECT tarea, count(estado) AS "TotalIncompletos" from tabla WHERE estado = 'Incompleto' GROUP BY tarea;
Query_2_result.png
My question is, how can I merge the above two queries into one query in order to produce a result similar to the following?
Expected_result.png
I have used UNION but I do not get the expected results. Attached is some sample code from the database I am using: Demo_DB
with q1 as (
SELECT tarea, count(estado) AS "TotalCompletos" from tabla WHERE estado = 'Completo' GROUP BY tarea
),
q2 as (
SELECT tarea, count(estado) AS "TotalIncompletos" from tabla WHERE estado = 'Incompleto' GROUP BY tarea
)
select tarea, coalesce("TotalCompletos", 0) as "TotalCompletos", coalesce("TotalIncompletos", 0) as "TotalIncompletos"
from q1 full join q2 using (tarea);

Temp Table VS Table variable

I have to write a table function so I prototyped the query in SQL Server and used a temp table but when I change it to a table variable the query goes from taking approx. 1 minute to more than 2 hours.
The second code is this one:
DECLARE #DETALLE TABLE
(
FECHA smalldatetime,
NO_OP NVARCHAR(100),
MONTO FLOAT,
PLAZO INT,
CLIENTE NVARCHAR(100)
)
-- CALCULO EL PLAZO POR EL MONTO, EL CUAL SERA EL NUMERADOR --
--DROP TABLE #DETALLE
INSERT INTO #DETALLE
SELECT
D.FECHA, D.NO_OP,
MONTO = (D.CAPITAL+D.INTERESES)/1000000,
PLAZO = CAST(D.FECHA_VCTO-D.FECHA AS INT),
CLIENTE = CASE
WHEN MIN_MAY = 'N' THEN 'MINORISTA'
WHEN M.ORIGEN = 'MESA LIQUIDEZ' THEN 'CLIENTE LIQUIDEZ'
WHEN M.ORIGEN IS NULL AND MIN_MAY = 'S' AND COD_SUCURSAL = '246' THEN 'EMPRESAS SALES'
ELSE 'OTRO MAYORISTA'
END
--INTO #DETALLE
FROM
BCI_RIF_ODS.dbo.Tab_Detalle_DAP AS D
INNER JOIN
BCI_RI_ODS.dbo.Cliente_Traduce AS C ON (C.CLIENTE_ID = D.CLIENTE_ID)
LEFT JOIN
BCI_RIF_ODS.dbo.TabMae_CliMesa AS M ON (D.CLIENTE_ID = M.CLIENTE_ID)
WHERE
FECHA >= '20180101' AND FECHA_VCTO > FECHA
SELECT
D1.CLIENTE, D1.FECHA,
NUMERADOR = SUM(D1.PLAZO*D1.MONTO),
MONTO = D2.MONTO,
FACTOR = SUM(D1.PLAZO*D1.MONTO)/D2.Monto
FROM
#DETALLE D1
LEFT JOIN
(SELECT
CLIENTE, FECHA,
MONTO = SUM(MONTO)
FROM
#DETALLE
GROUP BY
CLIENTE, FECHA) D2 ON (D1.CLIENTE = D2.CLIENTE AND D1.Fecha = D2.Fecha)
GROUP BY
D1.CLIENTE, D1.Fecha, D2.MONTO
You really don't need to make another copy of your data to then just perform an aggregate. You could use a cte here instead. Something like this will likely perform a lot better than copying data from one table to a variable.
with DETALLE as
(
-- CALCULO EL PLAZO POR EL MONTO, EL CUAL SERA EL NUMERADOR --
SELECT
D.FECHA, D.NO_OP,
MONTO = (D.CAPITAL+D.INTERESES)/1000000,
PLAZO = CAST(D.FECHA_VCTO-D.FECHA AS INT),
CLIENTE = CASE
WHEN MIN_MAY = 'N' THEN 'MINORISTA'
WHEN M.ORIGEN = 'MESA LIQUIDEZ' THEN 'CLIENTE LIQUIDEZ'
WHEN M.ORIGEN IS NULL AND MIN_MAY = 'S' AND COD_SUCURSAL = '246' THEN 'EMPRESAS SALES'
ELSE 'OTRO MAYORISTA'
END
FROM
BCI_RIF_ODS.dbo.Tab_Detalle_DAP AS D
INNER JOIN
BCI_RI_ODS.dbo.Cliente_Traduce AS C ON (C.CLIENTE_ID = D.CLIENTE_ID)
LEFT JOIN
BCI_RIF_ODS.dbo.TabMae_CliMesa AS M ON (D.CLIENTE_ID = M.CLIENTE_ID)
WHERE
FECHA >= '20180101' AND FECHA_VCTO > FECHA
)
SELECT
D1.CLIENTE, D1.FECHA,
NUMERADOR = SUM(D1.PLAZO*D1.MONTO),
MONTO = D2.MONTO,
FACTOR = SUM(D1.PLAZO*D1.MONTO)/D2.Monto
FROM
DETALLE D1
LEFT JOIN
(SELECT
CLIENTE, FECHA,
MONTO = SUM(MONTO)
FROM
DETALLE
GROUP BY
CLIENTE, FECHA) D2 ON (D1.CLIENTE = D2.CLIENTE AND D1.Fecha = D2.Fecha)
GROUP BY
D1.CLIENTE, D1.Fecha, D2.MONTO

How to select Specific Columns from same row in SQL Server

Here is my table funcionario:
ID_funcionario nome numero sexo morada email data_nasc
-----------------------------------------------------------------------
1 marcio 1234 male jardim marcio 11/23/2017
2 joel 3333 male bemfica ragy 11/25/2017
I want to select specifically only the nome "marcio" and number 1234.
For example, it should appear like this:
nome numero
----------------
marcio 1234
This is what I tried:
select *
from funcionario
where nome = 'marcio' and numero = '1234';
but that just shows me the whole row like this:
ID_funcionario nome numero sexo morada email data_nasc
----------------------------------------------------------------------
1 marcio 1234 male jardim marcio 11/23/2017
When you use select * ..., all the columns of the table are returned.
If you want to get only some columns, then you must be more specific, like this:
select nome, numero
from funcionario
where nome = 'marcio' and numero = '1234';
You are selecting every column by this:
SELECT * FROM ...
try to select the columns you need by:
select nome, numero from funcionario where nome ='marcio'and numero='1234';
In addition to the answers above, you could also write it this way:
select nome, numero
from funcionario
where nome = 'marcio'
It will return your desired result as well.
SELECT * FROM [TABLENAME] WHERE Col1 = ''
or
SELECT T_Col1, T_Col2 FROM [TABLENAME] WHERE T_Col1 = ''

Dynamic Temporal SQL Server 2005 Table by CASE

I need to define temporal table depending of value of parameter, I put this code:
CASE #estadoFacturacion
WHEN 1 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_pendiente(#custCod) --PROCESOS QUE NO TIENEN NINGUNA FACTURA ASOCIADA
WHEN 2 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_FactParcial(#custCod) --PROCESOS CON, AL MENOS, 1 TRAMO FACTURADO
WHEN 3 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_AbonoParcial(#custCod) --PROCESOS CON, AL MENOS, 1 TRAMO ABONADO
WHEN 4 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_Facturada(#custCod) --PROCESOS CON TODOS LOS TRAMOS FACTURADOS
WHEN 5 THEN SELECT * INTO #EstadoFacturacion FROM f_lineas_proceso_Abonada(#custCod) --PROCESOS CON TODOS LOS TRAMOS ABONADO
ELSE SELECT CONVERT(VARCHAR, LP.fk_proyecto_id) + '-' + CONVERT(VARCHAR,LP.linea) IdProyLinea INTO #EstadoFacturacion FROM lineas_proceso LP --TODOS LOS PROCESOS
But it doesn't works...
¿How can I do this?
Thanks.
SQL server does not have a CASE statement, only a CASE expression. So use an IF ELSE IF ladder instead:
IF #estadoFacturacion = 1
BEGIN
SELECT *
INTO #EstadoFacturacion
FROM f_lineas_proceso_pendiente(#custCod)
END
ELSE IF #estadoFacturacion = 2
BEGIN
SELECT *
INTO #EstadoFacturacion
FROM f_lineas_proceso_FactParcial(#custCod)
END
...
ELSE
BEGIN
SELECT CONVERT(VARCHAR, LP.fk_proyecto_id) + '-' + CONVERT(VARCHAR,LP.linea) Id
INTO #EstadoFacturacion
FROM lineas_proceso LP
END

Resources