How to get per hour in data set? - sql

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!

Related

Conversion error when adding additional clauses

need your expertise on the "Conversion failed when converting date and/or time from character string". Much written about it and tried looking though it and understanding it to the extend I could but it did not solve the issue.
My code includes a number on conversations from dates and strings to the common numerical format. The conversation work separately form the main code and even together when the code is loose. However, when I start adding more conditions in the "where" function, SQL doesn't seem to like it. Do you possible know how to handle it best? Any help is much appreciated.
SELECT DISTINCT
DOTWHL as "DC",
DORELD as "Release date",
DODLDT as "Prelim ETA",
DOITNO as "Item #",
MMITDS as "Item name",
MMSTCN as "Lkr",
DOPPQT as "Plan Qty",
DOPPQT/MMCFI2 as "Plan Qty, pall",
DOPSTS as "Sts",
SUM(MHFOQT) as "FC between ETA & BBD",
MLSTQT as "Stock, LHU",
MMCFI2 as "LHU/PAL",
MMCFI3 as "LHU/Layer",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN 'YES'
ELSE 'NO'
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN 'YES'
ELSE 'NO'
END
END AS "FEFO violation necessary?",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN SUM(MHFOQT)
ELSE MLSTQT
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN SUM(MHFOQT)
ELSE DOPPQT
END
END AS "Recommended Qty, LHU",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN SUM(MHFOQT)/MMCFI2
ELSE MLSTQT/MMCFI2
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN SUM(MHFOQT)/MMCFI2
ELSE DOPPQT/MMCFI2
END
END AS "Recommended Qty, pall",
MLBREF as "Batch",
CASE WHEN MLSTQT > DOPPQT
THEN CASE
WHEN DOPPQT < SUM(MHFOQT)
THEN SUM(MHFOQT)-DOPPQT
ELSE NULL
END
ELSE NULL
END AS "Fill Up possibility, LHU",
Sales.Sold_Qty as "Sold Qty 10 weeks",
Sales.Forecasted_Qty as "FC Qty 10 weeks",
ISNULL(Sales.Sold_Qty/NULLIF(Sales.Forecasted_Qty,0), 0) as "Sold/FC, %",
MBBUYE as "NP",
MMRESP as "DmP",
CASE
WHEN Other_Assortments.item <> 0 THEN 'Many Markets'
ELSE 'DC 091 only'
END as "Distributed on"
FROM MVXJDTA.MDOPLP
LEFT JOIN MVXJDTA.MITMAS
ON DOCONO=MMCONO AND DOITNO=MMITNO
LEFT JOIN MVXJDTA.MITBAL
ON DOCONO=MBCONO AND DOFWHL=MBWHLO AND DOITNO=MBITNO
LEFT JOIN MVXJDTA.MITSTA
ON DOCONO=MHCONO AND DOTWHL=MHWHLO AND DOITNO=MHITNO
LEFT JOIN MVXJDTA.MITLOC
ON DOCONO=MLCONO AND DOFWHL=MLWHLO AND DOITNO=MLITNO
LEFT JOIN
(
SELECT DISTINCT
MHITNO as "Item_#",
sum(MHSOQT) as "Sold_Qty",
sum(MHFOQT) as "Forecasted_Qty"
FROM MVXJDTA.MITSTA
WHERE MHCONO=1
AND MHWHLO='091'
AND MHCYP6 between
(cast(datepart(yyyy, dateadd(ww,-10,getdate())) as varchar) + right('00' + cast(datepart(ww, dateadd(ww,-10,getdate())) as varchar),2)) and
(cast(datepart(yyyy, dateadd(ww,-1,getdate())) as varchar) + right('00' + cast(datepart(ww, dateadd(ww,-1,getdate())) as varchar),2))
AND right(MHCYP6, 2) <>'00'
group by MHITNO
)
as Sales
on DOITNO=Sales.Item_#
LEFT JOIN
(
select distinct
OIITNO as "item"
from MVXJDTA.OCUSMA
left join MVXJDTA.OASCUS
on OKCONO=OCCONO and OKCUNO=OCCUNO
left join MVXJDTA.OASITN
on OKCONO=OICONO and OCASCD=OIASCD
where OKCONO=1
and OITDAT='99999999'
and OKCSCD<>'KR'
and OKCSCD<>'HK'
and OKCSCD<>'TW'
and OKCSCD<>'SG'
and OKCSCD<>'MY'
and OKCSCD<>'TH'
and OKCSCD<>'PH'
group by OIITNO) as Other_Assortments
on Other_Assortments.item=DOITNO
WHERE DOCONO=1
AND DOTWHL='091'
AND DOFWHL='010'
AND MHCYP6 NOT IN (
SELECT
MHCYP6
FROM MVXJDTA.MITSTA
WHERE MHWHLO='091'
AND MHCONO=1
AND RIGHT(CONVERT(VARCHAR, MHCYP6, 102), 2) ='00'
)
AND MHCYP6 BETWEEN
CASE
WHEN DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103))<10
THEN CONCAT( DATEPART(YEAR, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)), 0,
DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)))
ELSE CONCAT( DATEPART(YEAR, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)),
DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)))
END
CASE
WHEN MLBREF IS NULL
THEN '999999'
ELSE CASE
WHEN DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103)))<10
THEN CONCAT(DATEPART(YEAR, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))), 0,
DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))))
ELSE CONCAT(DATEPART(YEAR, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))),
DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))))
END
END
AND (MLSTQT-MLALQT)<>0
GROUP BY DOTWHL, DORELD, MLBREF, DODLDT, DOITNO, DOPPQT, MLSTQT, MMITDS, MLALQT, MBPLCD, MMSTCN, MMCFI2, MMCFI3, DOPSTS, Sales.Sold_Qty, Sales.Forecasted_Qty, MBBUYE, MMRESP, Other_Assortments.item
ORDER BY DOTWHL, DORELD

SQL Pivot with Union All

I'm using SQL Server 2012. I have 2 pivots (Current Year (CY) vs Last Year (LY) that work fine by themselves but want to Union them and have the results all togeather, how do I go about this? I need to have the data look like like this:
Cost Centre Name May_CY May_LY Jun_CY Jun LY.....This_Yr_Total Last_Yr_Total
This is my code:
SELECT
pvt.*,
Isnull(pvt.jan_CY, 0) +
Isnull(pvt.feb_CY, 0) +
Isnull(pvt.mar_CY, 0) +
Isnull(pvt.apr_CY, 0) +
Isnull(pvt.may_CY, 0) +
Isnull(pvt.jun_CY, 0) +
Isnull(pvt.jul_CY, 0) +
Isnull(pvt.aug_CY, 0) +
Isnull(pvt.sept_CY, 0) +
Isnull(pvt.oct_CY, 0) +
Isnull(pvt.nov_CY, 0) +
Isnull(pvt.Dec_CY, 0)
AS This_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2016_2017.AccDate), '_CY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_CY, Jun_CY, Jul_CY, Aug_CY, Sept_CY, Oct_CY, Nov_CY, Dec_CY, Jan_CY, Feb_CY, Mar_CY, Apr_CY)) AS pvt
UNION ALL
SELECT
pvt.*,
Isnull(pvt.jan_LY, 0) +
Isnull(pvt.feb_LY, 0) +
Isnull(pvt.mar_LY, 0) +
Isnull(pvt.apr_LY, 0) +
Isnull(pvt.may_LY, 0) +
Isnull(pvt.jun_LY, 0) +
Isnull(pvt.jul_LY, 0) +
Isnull(pvt.aug_LY, 0) +
Isnull(pvt.sept_LY, 0) +
Isnull(pvt.oct_LY, 0) +
Isnull(pvt.nov_LY, 0) +
Isnull(pvt.Dec_LY, 0)
AS Last_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2015_2016.AccDate), '_LY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2015_2016]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_LY, Jun_LY, Jul_LY, Aug_LY, Sept_LY, Oct_LY, Nov_LY, Dec_LY, Jan_LY, Feb_LY, Mar_LY, Apr_LY)) AS pvt
Any help would be greatly appreciated.
This is one of the pivots for 'This Year' that returns results:
SELECT
pvt.*,
Isnull(
pvt.jan,0)+ Isnull(pvt.feb,0)+ Isnull(pvt.mar,0)+ Isnull(pvt.apr,0)+ Isnull(pvt.may,0)+ Isnull(pvt.jun,0)+ Isnull(pvt.jul,0)+
Isnull(pvt.aug,0)+ Isnull(pvt.sept,0)+ Isnull(pvt.oct,0)+ Isnull(pvt.nov,0) AS This_Year_Total
FROM
(
SELECT
[CostCentre],
[CostCentreDesc] AS Name,
CONVERT(
CHAR(4),
AccDate,
100
) AS [Month],
[RecordedAmount]
FROM
[tblGLS215_2016_2017]
) AS s PIVOT(
SUM( [RecordedAmount] ) FOR [Month] IN(
May,
Jun,
Jul,
Aug,
Sept,
Oct,
Nov,
DEC, Jan, Feb, Mar, Apr)) AS pvt
Select A.[CostCentre], A.Name
,A.[May_CY],B.[May_LY]
,A.[Jun_CY],B.[Jun_LY]
,A.[Jul_CY],B.[Jul_LY]
,A.[Aug_CY],B.[Aug_LY]
,A.[Sept_CY],B.[Sept_LY]
,A.[Oct_CY],B.[Oct_LY]
,A.[Nov_CY],B.[Nov_LY]
,A.[Dec_CY],B.[Dec_LY]
,A.[Jan_CY],B.[Jan_LY]
,A.[Feb_CY],B.[Feb_LY]
,A.[Mar_CY],B.[Mar_LY]
,A.[Apr_CY],B.[Apr_LY]
,A.[This_Year] as This_Yr_Total , B.[Last_Year] as Last_Yr_Total
From
(
SELECT
pvt.*,
Isnull(pvt.jan_CY, 0) +
Isnull(pvt.feb_CY, 0) +
Isnull(pvt.mar_CY, 0) +
Isnull(pvt.apr_CY, 0) +
Isnull(pvt.may_CY, 0) +
Isnull(pvt.jun_CY, 0) +
Isnull(pvt.jul_CY, 0) +
Isnull(pvt.aug_CY, 0) +
Isnull(pvt.sept_CY, 0) +
Isnull(pvt.oct_CY, 0) +
Isnull(pvt.nov_CY, 0) +
Isnull(pvt.Dec_CY, 0)
AS This_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2016_2017.AccDate), '_CY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_CY, Jun_CY, Jul_CY, Aug_CY, Sept_CY, Oct_CY, Nov_CY, Dec_CY, Jan_CY, Feb_CY, Mar_CY, Apr_CY)) AS pvt
)as A
full outer Join
(
SELECT
pvt.*,
Isnull(pvt.jan_LY, 0) +
Isnull(pvt.feb_LY, 0) +
Isnull(pvt.mar_LY, 0) +
Isnull(pvt.apr_LY, 0) +
Isnull(pvt.may_LY, 0) +
Isnull(pvt.jun_LY, 0) +
Isnull(pvt.jul_LY, 0) +
Isnull(pvt.aug_LY, 0) +
Isnull(pvt.sept_LY, 0) +
Isnull(pvt.oct_LY, 0) +
Isnull(pvt.nov_LY, 0) +
Isnull(pvt.Dec_LY, 0)
AS Last_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2015_2016.AccDate), '_LY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2015_2016]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_LY, Jun_LY, Jul_LY, Aug_LY, Sept_LY, Oct_LY, Nov_LY, Dec_LY, Jan_LY, Feb_LY, Mar_LY, Apr_LY)) AS pvt
) as B
On A.[CostCentre]=B.[CostCentre] and A.Name=B.Name

SQL Query not producing 'Disabled' jobs within the results, alongside 'Failed' jobs

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.

How to reduce code redundancy in this query?

I've got these two calculated fields in my query:
CASE
WHEN TRN.TOTAL_VALUE_T = 0 THEN '00000000000'
ELSE
CASE
WHEN CC.PORT_CURRENCY1 = 'CAD' THEN RIGHT('00000000000' + REPLACE(LTRIM(STR(TRN.TOTAL_VALUE_T + TRN.TAXES, 11, 2)), '.', ''), 11)
WHEN CC.PORT_CURRENCY1 = 'USD' THEN RIGHT('00000000000' + REPLACE(LTRIM(STR((TRN.TOTAL_VALUE_T + TRN.TAXES) * DBO.fnGetExchangeRate(TRN.TRADE_DATE, 'USD', 'CAD'), 11, 2)), '.', ''), 11)
END
END AS TX_PRIX_CAD,
CASE
WHEN T.TRANS_TYPE in ('ADD','DELIV') THEN
CASE
WHEN (SELECT currencyTitle FROM DBO.GetPrice(TRN.SEC_NO, TRN.TRADE_DATE)) = '' THEN TX_PRIX_CAD
END
END AS TX_MNT_BRUT
You see, the second field (TX_MNT_BRUT) must equal the first one (TX_PRIX_CAD) under certain conditions.
Problem when doing this is SQL is telling me that TX_PRIX_CAD is not a valid column name, I guess because the column name does not exist physically in the table.
How could I achieve this without repeating the code in TX_PRIX_CAD in TX_MNT_BRUT ?
Thanks.
You probably need to nest the select statement e.g.
SELECT <other_columns>, TX_PRIX_CAD,
CASE
WHEN T.TRANS_TYPE in ('ADD','DELIV') THEN
CASE
WHEN (SELECT currencyTitle FROM DBO.GetPrice(TRN.SEC_NO, TRN.TRADE_DATE)) = '' THEN TX_PRIX_CAD
END
END AS TX_MNT_BRUT
FROM (
SELECT
<other columns>,
CASE
WHEN TRN.TOTAL_VALUE_T = 0 THEN '00000000000'
ELSE
CASE
WHEN CC.PORT_CURRENCY1 = 'CAD' THEN RIGHT('00000000000' + REPLACE(LTRIM(STR(TRN.TOTAL_VALUE_T + TRN.TAXES, 11, 2)), '.', ''), 11)
WHEN CC.PORT_CURRENCY1 = 'USD' THEN RIGHT('00000000000' + REPLACE(LTRIM(STR((TRN.TOTAL_VALUE_T + TRN.TAXES) * DBO.fnGetExchangeRate(TRN.TRADE_DATE, 'USD', 'CAD'), 11, 2)), '.', ''), 11)
END
END
END AS TX_PRIX_CAD,
T.TRANS_TYPE
FROM <table_name>
)

How SQL calculates NEXT_RUN_DATE for a job schedule?

I have to make a manual calculation of the next run date for a job, can you help me?
to get the next run date for a job you can use then sysschedules and sysjobschedules tables
check the next_run_date and next_runtime columns from the table sysjobschedules
next_run_date int Next date on which
the job is scheduled to run. The date
is formatted YYYYMMDD.
next_run_time int Time at which the
job is scheduled to run. The time is
formatted HHMMSS, and uses a 24-hour
clock.
see this script
Select sched.*,jobsched.* FROM msdb.dbo.sysschedules AS sched
inner Join msdb.dbo.sysjobschedules AS jobsched ON sched.schedule_id = jobsched.schedule_id
or you can use the msdb.dbo.sp_help_jobschedule stored procedure, to get the same info.
UPDATE
if you need calculate manually the next_run_date you must check the sysschedules table and see the freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_start_time columns to determine the formula.
check this link to see an example of use.
Check this one:
SELECT
J.NAME JOB,
DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112))))
JOB_STARTED,
DATEADD(SS,((H.RUN_DURATION)%10000)%100,DATEADD(N,((H.RUN_DURATION)%10000)/100,DATEADD(HH,(H.RUN_DURATION)/10000,DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112)))))))
JOB_COMPLETED,
CONVERT(VARCHAR(2),(H.RUN_DURATION)/10000) + ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)/100)+ ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)%100) RUN_DURATION,
CASE H.RUN_STATUS
WHEN 0 THEN 'FAILED'
WHEN 1 THEN 'SUCCEEDED'
WHEN 2 THEN 'RETRY'
WHEN 3 THEN 'CANCELED'
WHEN 4 THEN 'IN PROGRESS'
END RUN_STATUS
,CASE S.FREQ_TYPE
WHEN 1 THEN 'ONCE'
WHEN 4 THEN ' DAILY'
WHEN 8 THEN ' WEEKLY'
WHEN 16 THEN ' MONTHLY'
WHEN 32 THEN ' MONTHLY RELATIVE'
WHEN 64 THEN ' WHEN SQL SERVER'
ELSE 'N/A' END [FREQ]
,CASE
WHEN S.NEXT_RUN_DATE > 0 THEN DATEADD(N,(NEXT_RUN_TIME%10000)/100,DATEADD(HH,NEXT_RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),NEXT_RUN_DATE),112)))
ELSE CONVERT(DATETIME,CONVERT(VARCHAR(8),'19000101'),112) END NEXT_RUN
FROM
MSDB..SYSJOBHISTORY H,
MSDB..SYSJOBS J,
MSDB..SYSJOBSCHEDULES S,
(
SELECT
MAX(INSTANCE_ID) INSTANCE_ID
,JOB_ID
FROM MSDB..SYSJOBHISTORY GROUP BY JOB_ID
) M
WHERE
H.JOB_ID = J.JOB_ID
AND
J.JOB_ID = S.JOB_ID
AND
H.JOB_ID = M.JOB_ID
AND
H.INSTANCE_ID = M.INSTANCE_ID
-- IF you want to check all job for today then uncomments below
-- AND
-- RUN_DATE = (YEAR(GETDATE())*10000) + (MONTH(GETDATE()) * 100) + DAY(GETDATE())
ORDER BY NEXT_RUN
The short answer is that there's no single formula - it varies by value of freq_type.
The site seems to be down at the moment of writing, but there is an article at http://www.sqlmag.com/Article/ArticleID/99593/sql_server_99593.html which covers how to derive this information. Unfortunately, the site doesn't allow Google to cache its content, so it can't be retrieved until the site comes back up
This looks like a decent alternative source for the kind of query you're trying to write.
here is a very nice script where you can get the next run date.
-- http://www.sqlprofessionals.com/blog/sql-scripts/2014/10/06/insight-into-sql-agent-job-schedules/
SELECT [JobName] = [jobs].[name]
,[Enabled] = CASE [jobs].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Scheduled] = CASE [schedule].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Next_Run_Date] =
CASE [jobschedule].[next_run_date]
WHEN 0 THEN CONVERT(DATETIME, '1900/1/1')
ELSE CONVERT(DATETIME, CONVERT(CHAR(8), [jobschedule].[next_run_date], 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [jobschedule].[next_run_time]), 6), 5, 0, ':'), 3, 0, ':'))
END
,[Category] = [categories].[name]
,[Owner] = SUSER_SNAME([jobs].[owner_sid])
,[Description] = [jobs].[description]
,[Occurs] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Daily'
WHEN 8 THEN 'Weekly'
WHEN 16 THEN 'Monthly'
WHEN 32 THEN 'Monthly relative'
WHEN 64 THEN 'When SQL Server Agent starts'
WHEN 128 THEN 'Start whenever the CPU(s) become idle'
ELSE ''
END
,[Occurs_detail] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'O'
WHEN 4 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' day(s)'
WHEN 8 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' weeks(s) on ' +
LEFT(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END ,
LEN(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END
) - 1
)
WHEN 16 THEN 'Day ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
WHEN 32 THEN 'The ' +
CASE [schedule].[freq_relative_interval]
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 4 THEN 'Third'
WHEN 8 THEN 'Fourth'
WHEN 16 THEN 'Last'
END +
CASE [schedule].[freq_interval]
WHEN 1 THEN ' Sunday'
WHEN 2 THEN ' Monday'
WHEN 3 THEN ' Tuesday'
WHEN 4 THEN ' Wednesday'
WHEN 5 THEN ' Thursday'
WHEN 6 THEN ' Friday'
WHEN 7 THEN ' Saturday'
WHEN 8 THEN ' Day'
WHEN 9 THEN ' Weekday'
WHEN 10 THEN ' Weekend Day'
END + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
ELSE ''
END
,[Frequency] =
CASE [schedule].[freq_subday_type]
WHEN 1 THEN 'Occurs once at ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 2 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Seconds(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 4 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Minute(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 8 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Hour(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
ELSE ''
END
,[AvgDurationInSec] = CONVERT(DECIMAL(10, 2), [jobhistory].[AvgDuration])
FROM [msdb].[dbo].[sysjobs] AS [jobs] WITh(NOLOCK)
LEFT OUTER JOIN [msdb].[dbo].[sysjobschedules] AS [jobschedule] WITh(NOLOCK)
ON [jobs].[job_id] = [jobschedule].[job_id]
LEFT OUTER JOIN [msdb].[dbo].[sysschedules] AS [schedule] WITh(NOLOCK)
ON [jobschedule].[schedule_id] = [schedule].[schedule_id]
INNER JOIN [msdb].[dbo].[syscategories] [categories] WITh(NOLOCK)
ON [jobs].[category_id] = [categories].[category_id]
LEFT OUTER JOIN
( SELECT [job_id], [AvgDuration] = (SUM((([run_duration] / 10000 * 3600) +
(([run_duration] % 10000) / 100 * 60) +
([run_duration] % 10000) % 100)) * 1.0) / COUNT([job_id])
FROM [msdb].[dbo].[sysjobhistory] WITh(NOLOCK)
WHERE [step_id] = 0
GROUP BY [job_id]
) AS [jobhistory]
ON [jobhistory].[job_id] = [jobs].[job_id];