I've a set of 6 Viewsthat i use to gather the data i need for an excel report.
View 1
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Gabbiano.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
UNION ALL
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Istantravel.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
UNION ALL
SELECT *, MONTH(DataEmissione) AS Mese_Emissione, YEAR(DataEmissione) AS Anno_Emissione, CASE WHEN StatoEmissione = 'R' THEN - ImpVetComp WHEN StatoBiglietto = 'VR' THEN ImpVetComp * 0 WHEN StatoEmissione = 'NC' THEN ImpVetComp * 0 WHEN StatoEmissione = 'AN' THEN ImpVetComp * 0 ELSE ImpVetComp END AS Fare, DATENAME(month, DataEmissione) AS Issue_Month_Name, DATEPART(quarter, DataEmissione) AS Quarter, YEAR(DATEADD(month, - 3, DataEmissione)) AS AnnoFiscale, CASE WHEN MONTH(DataEmissione) < 4 THEN MONTH(DataEmissione) + 9 ELSE MONTH(DataEmissione) - 3 END AS Fiscal_Month, REPLACE(REPLACE(Destinazione, ' ', ''), '-', '') AS Destinazione_Normalizzata
FROM Globmaster.dbo.PRAB0000
WHERE (DataEmissione >= DATEADD(year, - 3, GETDATE()))
Views 2
SELECT biglietti.Agenzia, biglietti.CodiceCompagnia, biglietti.StatoBiglietto, biglietti.StatoEmissione, biglietti.CodicePersonale, biglietti.TipoTratta, biglietti.ClasseVettore, biglietti.MastroCliente, biglietti.SottocCliente,
biglietti.DataEmissione, biglietti.DataVariazione, biglietti.DataPartenza, biglietti.ImponibileVettore, biglietti.TasseAerop, biglietti.ImpCorrispettivi, biglietti.CorrispettiviAdd, biglietti.ScontoCommissioni,
biglietti.NumeroPax, biglietti.Destinazione, biglietti.ImpVetComp, biglietti.ImportoComm, biglietti.ImportoCommPass, biglietti.NumeroBiglietto, biglietti.NomePasseggero, biglietti.TasseYQ, biglietti.TasseYR,
biglietti.CodicePnr, biglietti.Mese_Emissione, biglietti.Anno_Emissione, biglietti.Fare, biglietti.Nome_Mese_Emissione, biglietti.Quarter, biglietti.Prop, biglietti.AnnoFiscale,
compagnie.Descrizione AS NomeCompagnia, compagnie.Categoria, compagnie.Alleanza,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, 1, 3) END AS Partenza,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, LEN(biglietti.Destinazione_Normalizzata)
/ 2 + 1 - 3, 3) END AS Arrivo,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE SUBSTRING(biglietti.Destinazione_Normalizzata, LEN(biglietti.Destinazione_Normalizzata)
/ 2 + 1, 3) END AS DestinazioneFinale,
CASE WHEN biglietti.Destinazione_Normalizzata = 'VOID' THEN 'VOID' WHEN biglietti.Destinazione_Normalizzata = 'CNJ' THEN 'CAMBI' WHEN biglietti.Destinazione_Normalizzata = 'conj' THEN 'CONGIUNZIONI'
WHEN datalength(biglietti.Destinazione_Normalizzata)
= 0 THEN 'NON INDICATA' WHEN biglietti.Destinazione_Normalizzata LIKE 'OR.ISSUE%' THEN 'RIEMISSIONI' ELSE RIGHT(biglietti.Destinazione_Normalizzata, 3) END AS Ritorno, biglietti.Mese_Fiscale,
biglietti.Destinazione_Normalizzata, biglietti.CodiceBiglietto
FROM dbo.Biglietti AS biglietti INNER JOIN
dbo.Compagnie AS compagnie ON biglietti.CodiceCompagnia = compagnie.Codice
WHERE (biglietti.DataEmissione >= DATEADD(year, - 3, GETDATE()))
And the other Views are similar.
Each is needed to performs calculations columns added with each Views.
However i reckon it's a bit inefficient.
How you would solve this?
Related
I'm trying to get data per hour however as I execute, the data for day is displayed in the table. IDC_YMD with per hour result must be in the table and I'm not sure if I have the right SUBSTR(string, start, length).
SELECT EQP_ID, EQP_NAME, 'WorkPreparation' GUBUN,WorkPreparation
CNT,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM
(
SELECT CASE WHEN WorkPreparation = 0 THEN '-' ELSE EQP_ID END AS EQP_ID, CASE WHEN WorkPreparation =
0 THEN '-' ELSE SUBSTR(EQP_NAME,1,4) END AS EQP_NAME,
WorkPreparation,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM(
SELECT EQP_ID, EVENT_COMMENT EQP_NAME, SUM(WORK_PRE_CNT) WorkPreparation, A.SITE_CODE
, A.GODS_CODE
, A.EES_STEP_ID AS STEP_NAME
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2))) || '/' || TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12,
2))) AS IDC_YMD
, 'D' AS IDC_SUMR_UNIT_CODE
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) = 0
THEN ROUND(SUM(NVL(A.OPER_MOP, 0)),1)
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) /
60,1)
END AS MTBI
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) + SUM(NVL(A.WORK_PRE_CNT, 0)) +
SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT, 0)) +
SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) = 0
THEN 0
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) +
SUM(NVL(A.WORK_PRE_CNT, 0)) + SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT,
0)) + SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) / 60,1)
END AS MTBA
FROM IFR_EES_PCL A
WHERE SITE_CODE = 'E502AA'
AND GODS_CODE = 'N5210'
AND MTBI_MNG_YN = 'Y'
AND EES_STEP_ID = 'TP'
AND A.IDC_YMD BETWEEN TO_CHAR(SYSDATE-6, 'YYYYMMDDHH') AND TO_CHAR(SYSDATE, 'YYYYMMDD')
GROUP BY EQP_ID, EVENT_COMMENT,A.SITE_CODE
, A.GODS_CODE
,A.EQP_TYPE
, A.EES_STEP_ID
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
, A.IDC_YMD
ORDER BY A.IDC_YMD, MTBI DESC--TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
))
WHERE ROWNUM <= 10
and EQP_NAME like 'TA%'
Thank you!
I want to replace the 1st and 2nd parameter in DATEADD function depending on the result of cteTable. Is this something possible? Do I need to create a parameter? Thank you in advance. Happy new year!
;with cteDP as(
SELECT CODE, MEASSUREMENT, DEFEXPIRYDATEDAYS,
CASE WHEN MEASSUREMENT = 0 THEN 'DAY'
WHEN MEASSUREMENT = 1 THEN 'WEEK'
WHEN MEASSUREMENT = 2 THEN 'MONTH'
WHEN MEASSUREMENT = 3 THEN 'YEARS'
ELSE 'SECOND'
END AS MEASUREMENTINWORD
FROM PW001C06 C06 WHERE CODE IN ('ADC','MMC')
)
select * from cteDP
UPDATE P05
SET P05.EXPIRYDATE = CASE
WHEN P05.CODE = 'ADC' THEN DATEADD('cteDocProperties.MEASUREMENTINWORD', #2nd parameter, EXPIRYDATE)
-- WHEN P05.CODE = 'MMC' THEN DATEADD(YEAR, 4, EXPIRYDATE)
-- WHEN P05.CODE = 'LD00' THEN DATEADD(YEAR, 3, EXPIRYDATE)
ELSE EXPIRYDATE
END
FROM PW001P05 P05
INNER JOIN cteDP
ON cteDP.CODE = P05.CODE
WHERE P05.PIN = 1
AND P05.CODE IN ('ADC','MMC')
You can directly JOIN to the table expression:
UPDATE P05
SET
P05.EXPIRYDATE = CASE
WHEN P05.CODE = 'ADC' THEN
CASE WHEN MEASUREMENTINWORD = 'SECOND'
THEN DATEADD(SECOND, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'DAY'
THEN DATEADD(DAY, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'MONTH'
THEN DATEADD(MONTH, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'YEAR'
THEN DATEADD(YEAR, MEASSUREMENT, EXPIRYDATE)
ELSE EXPIRYDATE
END
FROM PW001P05 P05
INNER JOIN
(
SELECT
CODE
, MEASSUREMENT
, DEFEXPIRYDATEDAYS
, CASE
WHEN MEASSUREMENT = 0 THEN 'DAY'
WHEN MEASSUREMENT = 1 THEN 'WEEK'
WHEN MEASSUREMENT = 2 THEN 'MONTH'
WHEN MEASSUREMENT = 3 THEN 'YEARS'
ELSE 'SECOND'
END AS MEASUREMENTINWORD
FROM PW001C06 C06 WHERE CODE IN ('ADC','MMC')
) cteDP
ON cteDP.CODE = P05.CODE
WHERE P05.PIN = 1
AND P05.CODE IN ('ADC','MMC')
I am trying to join these two tables, or use a sub-query to achieve the results I need.
As of now I have the first query pulling hourly totals with a overall total between MIN(time) and MAX(time). I need to join the second query to get the total scans from MIN(time) and MAX(time)
Any ideas of where I could be going wrong?
select
UPPER(t.operator) as Operator,
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END)) ELSE NULL END AS '6AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END)) ELSE NULL END AS '7AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END)) ELSE NULL END AS '8AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END)) ELSE NULL END AS '9AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END)) ELSE NULL END AS '10AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END)) ELSE NULL END AS '11AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END)) ELSE NULL END AS '12PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END)) ELSE NULL END AS '1PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END)) ELSE NULL END AS '2PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END)) ELSE NULL END AS '3PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END)) ELSE NULL END AS '4PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END)) ELSE NULL END AS '5PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (COUNT(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN t.eventtype ELSE NULL END)) ELSE NULL END AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
CAST(t.time as DATE) = CAST(GETDATE() as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator,
t.eventtype
Second query:
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
CAST(o.time as DATE) = CAST(GETDATE() as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
order by o.operator
Something like the below should get you headed to a solution. I removed the group on t.eventtype and removed from the case statements because the where clause already limited the results for you.
select
op.Operator,
op.TotalScans,
op.LogonTime,
op.TotalMinLogon,
b.[6AM],
b.[7AM],
b.[8AM],
b.[9AM],
b.[10AM],
b.[11AM],
b.[12PM],
b.[1PM],
b.[2PM],
b.[3PM],
b.[4PM],
b.[5PM],
b.[6+PM]
from
(
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
) as op
left join
(
select
UPPER(t.operator) as Operator,
SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END) AS '6AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END) AS '7AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END) AS '8AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END) AS '9AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END) AS '10AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END) AS '11AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END) AS '12PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END) AS '1PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END) AS '2PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END) AS '3PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END) AS '4PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END) AS '5PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN 1 ELSE 0 END) AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator
) as b
on b.Operator = op.Operator
SELECT l.* ,
r.TotalScans ,
r.LogonTime ,
r.TotalMinLogon
FROM ( SELECT UPPER(t.operator) AS Operator ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 6
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '6AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 7
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '7AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 8
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '8AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 9
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '9AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 10
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '10AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 11
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '11AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 12
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '12PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 13
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '1PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 14
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '2PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 15
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '3PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 16
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '4PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 17
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '5PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( COUNT(CASE WHEN DATEPART(HOUR, t.time) > 17
THEN t.eventtype
ELSE NULL
END) )
ELSE NULL
END AS '6+PM' ,
SUM(CASE WHEN t.eventtype = 'Replenishment Complete'
THEN 1
ELSE 0
END) AS TotalCanisters
FROM #replevent t
WHERE CAST(t.time AS DATE) = CAST(GETDATE() AS DATE)
AND t.stationtype IN ( 'T', 'S' )
AND t.eventtype = 'Replenishment Complete'
GROUP BY t.operator ,
t.eventtype
) AS l
INNER JOIN ( SELECT UPPER(o.operator) AS Operator_r ,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1
ELSE 0
END) AS TotalScans ,
CONVERT(VARCHAR(19), MIN(o.time), 8) AS LogonTime ,
DATEDIFF(SECOND, MIN(o.time), MAX(o.time)) AS TotalMinLogon
FROM #replevent o
WHERE CAST(o.time AS DATE) = CAST(GETDATE() AS DATE)
AND o.eventtype IN ( 'Replenishment Complete',
'GoodScan' )
GROUP BY o.operator
) AS r ON l.Operator = r.Operator_r
ORDER BY l.Operator;
I have the following code for a SQL Query I'm working on..
DECLARE #Date datetime
SET #Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
DECLARE #jobHistory TABLE
(
job_id UNIQUEIDENTIFIER
, success INT
, cancel INT
, fail INT
, retry INT
, last_execution_id INT
, last_duration CHAR(8)
, last_execution_start DATETIME
);
WITH lastExecution
AS
(
SELECT job_id
, MAX(instance_id) AS last_instance_id
FROM msdb.dbo.sysjobhistory
WHERE step_id = 0
GROUP BY job_id
)
INSERT INTO #jobHistory
SELECT sjh.job_id
, SUM(CASE WHEN sjh.run_status = 1 AND step_id = 0 THEN 1 ELSE 0 END) AS success
, SUM(CASE WHEN sjh.run_status = 3 AND step_id = 0 THEN 1 ELSE 0 END) AS cancel
, SUM(CASE WHEN sjh.run_status = 0 AND step_id = 0 THEN 1 ELSE 0 END) AS fail
, SUM(CASE WHEN sjh.run_status = 2 THEN 1 ELSE 0 END) AS retry
, MAX(CASE WHEN sjh.step_id = 0 THEN instance_id ELSE NULL END) last_execution_id
, SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),2,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),4,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),6,2)
AS last_duration
, MAX(CASE WHEN le.last_instance_id IS NOT NULL THEN
CONVERT(datetime, RTRIM(run_date))
+ ((run_time / 10000 * 3600)
+ ((run_time % 10000) / 100 * 60)
+ (run_time % 10000) % 100) / (86399.9964)
ELSE '1900-01-01' END) AS last_execution_start
FROM msdb.dbo.sysjobhistory AS sjh
LEFT JOIN lastExecution AS le
ON sjh.job_id = le.job_id
AND sjh.instance_id = le.last_instance_id
GROUP BY sjh.job_id;
DECLARE #weekDay TABLE (
mask INT
, maskValue VARCHAR(32)
);
INSERT INTO #weekDay
SELECT 1, 'Sunday' UNION ALL
SELECT 2, 'Monday' UNION ALL
SELECT 4, 'Tuesday' UNION ALL
SELECT 8, 'Wednesday' UNION ALL
SELECT 16, 'Thursday' UNION ALL
SELECT 32, 'Friday' UNION ALL
SELECT 64, 'Saturday';
WITH myCTE
AS(
SELECT sched.name AS 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, CASE
WHEN sched.freq_type = 1
THEN 'Once'
WHEN sched.freq_type = 4
AND sched.freq_interval = 1
THEN 'Daily'
WHEN sched.freq_type = 4
THEN 'Every ' + CAST(sched.freq_interval AS VARCHAR(5)) + ' days'
WHEN sched.freq_type = 8 THEN
REPLACE( REPLACE( REPLACE((
SELECT maskValue
FROM #weekDay AS x
WHERE sched.freq_interval & x.mask <> 0
ORDER BY mask FOR XML RAW)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; weekly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' weeks' END
WHEN sched.freq_type = 16 THEN 'On day '
+ CAST(sched.freq_interval AS VARCHAR(10)) + ' of every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
WHEN sched.freq_type = 32 THEN
CASE
WHEN sched.freq_relative_interval = 1 THEN 'First'
WHEN sched.freq_relative_interval = 2 THEN 'Second'
WHEN sched.freq_relative_interval = 4 THEN 'Third'
WHEN sched.freq_relative_interval = 8 THEN 'Fourth'
WHEN sched.freq_relative_interval = 16 THEN 'Last'
END +
CASE
WHEN sched.freq_interval = 1 THEN ' Sunday'
WHEN sched.freq_interval = 2 THEN ' Monday'
WHEN sched.freq_interval = 3 THEN ' Tuesday'
WHEN sched.freq_interval = 4 THEN ' Wednesday'
WHEN sched.freq_interval = 5 THEN ' Thursday'
WHEN sched.freq_interval = 6 THEN ' Friday'
WHEN sched.freq_interval = 7 THEN ' Saturday'
WHEN sched.freq_interval = 8 THEN ' Day'
WHEN sched.freq_interval = 9 THEN ' Weekday'
WHEN sched.freq_interval = 10 THEN ' Weekend'
END
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; monthly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
END
WHEN sched.freq_type = 64 THEN 'StartUp'
WHEN sched.freq_type = 128 THEN 'Idle'
END AS 'frequency'
, ISNULL('Every ' + CAST(sched.freq_subday_interval AS VARCHAR(10)) +
CASE
WHEN sched.freq_subday_type = 2 THEN ' seconds'
WHEN sched.freq_subday_type = 4 THEN ' minutes'
WHEN sched.freq_subday_type = 8 THEN ' hours'
END, 'Once') AS 'subFrequency'
, REPLICATE('0', 6 - LEN(sched.active_start_time))
+ CAST(sched.active_start_time AS VARCHAR(6)) AS 'startTime'
, REPLICATE('0', 6 - LEN(sched.active_end_time))
+ CAST(sched.active_end_time AS VARCHAR(6)) AS 'endTime'
, REPLICATE('0', 6 - LEN(jobsched.next_run_time))
+ CAST(jobsched.next_run_time AS VARCHAR(6)) AS 'nextRunTime'
, CAST(jobsched.next_run_date AS CHAR(8)) AS 'nextRunDate'
FROM msdb.dbo.sysschedules AS sched
JOIN msdb.dbo.sysjobschedules AS jobsched
ON sched.schedule_id = jobsched.schedule_id
WHERE sched.enabled = 1
)
SELECT job.name AS [Job Name]
, CASE WHEN job.enabled = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Job Status]
, COALESCE(sched.subFrequency, '') AS [Frequency]
, COALESCE(jh.last_duration, '') AS [Last Run Duration]
, COALESCE(jh.last_execution_start, '') AS [Last Run Time/Date]
FROM msdb.dbo.sysjobs AS job
LEFT JOIN myCTE AS sched
ON job.job_id = sched.job_id
LEFT JOIN #jobHistory AS jh
ON job.job_id = jh.job_id
WHERE jh.last_execution_start >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND job.name like '%MAINTENANCE - BACKUP%'
ORDER BY nextRunDate;
but although the results show the expected 'Failed' jobs, the 'Disabled' jobs are missing. I have also had help with this, as I have no SQL experience.
This Query has been created to check the Job History of roughtly 5/10 Backup Jobs within a 24 hour period, noting all the Failures (even if the last Run Succeeded). The seconds on the [Last Run Time/Date] also seem to be off, showing as soemthign like '50:00.0'
I also need a new column for the [Last Run Outcome] - to show if the Job 'Failed/Succeeded' as a Status.
Please let me know if you require any further information or a PasteBin of my code.
WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
n this query i want to add one more condition like
AND LocType = 'Retail Store' and TotalHrs=0 but showing error
Invalid column name 'TotalHrs'.
How i can resolve this issue.if any help is very appreciable,thanks in advance
You can use multiple CTE's in following:
WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
, cte2 AS
(
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
)
SELECT *
FROM cte2
WHERE TotalHrs=0 --your alias condition or you can move all where clause here