SQLServer Jobhistory - last successful runtime & last unsuccessful runtime - sql

I want to have a view about my sql jobs which contains
name
job_id
run_date
LastSuccessfulRunDate
This is what I found for the last successful run dates.
Works like a charm, but here I am, failing to add the last run date.
Use msdb
GO
SELECT
SJ.NAME AS [Job Name]
,RUN_STATUS AS [Run Status]
,MAX(DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME)) AS [Last Time Job Ran On]
FROM
dbo.SYSJOBS SJ
LEFT OUTER JOIN dbo.SYSJOBHISTORY JH
ON SJ.job_id = JH.job_id
WHERE JH.step_id = 0
AND jh.run_status = 1
GROUP BY SJ.name, JH.run_status
ORDER BY [Last Time Job Ran On] DESC
GO
Here's what I got so far but it's giving me the result in two lines, one with last run date and the other with last successful run (which is als incorrect because it selects the highest date there is - distinct value). I kindly ask for help to get the join right and the result in one line.
USE msdb
GO
SELECT DISTINCT SJ.Name AS JobName,
SJH.run_date AS LastRunDate,
SJH.job_id,
(SELECT MAX(DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME))
FROM sysjobs
RIGHT JOIN sysjobhistory
ON SJ.job_id = SJH.job_id
WHERE SJH.run_status = 1) AS LastSuccessfulRun,
CASE SJH.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Successful'
WHEN 3 THEN 'Cancelled'
WHEN 4 THEN 'In Progress'
END AS LastRunStatus
FROM sysjobhistory SJH, sysjobs SJ
WHERE SJH.job_id = SJ.job_id and SJH.run_date =
(SELECT MAX(SJH.run_date) FROM sysjobhistory SJH WHERE SJ.job_id = SJH.job_id)

I think you want row_number():
SELECT x.*
FROM (SELECT SJ.NAME AS [Job Name], RUN_STATUS AS [Run Status],
DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) AS LastRunDateTime,
ROW_NUMBER() OVER (PARTITION BY SJ.NAME ORDER BY DBO.AGENT_DATETIME(RUN_DATE, RUN_TIME) DESC) as seqnum
FROM dbo.SYSJOBS SJ LEFT OUTER JOIN
dbo.SYSJOBHISTORY JH
ON SJ.job_id = JH.job_id
WHERE JH.step_id = 0 AND jh.run_status = 1
GROUP BY SJ.name, JH.run_status
) x
WHERE seqnum = 1
ORDER BY LastRunDateTime DESC;
Also, learn to use proper, explicit JOIN syntax. Commas in the FROM clause are archaic.

solution is:
SELECT sj.name,
MAX(dbo.agent_datetime(sjh.run_date, sjh.run_time)) AS last_Succesful_run,
x.last_Unsuccesful_run
FROM sysjobhistory sjh
INNER JOIN sysjobs sj ON sjh.job_id = sj.job_id
LEFT OUTER JOIN
(SELECT sysjobs.name,
MAX(dbo.agent_datetime(sysjobhistory.run_date, sysjobhistory.run_time)) AS last_Unsuccesful_run
FROM sysjobhistory
INNER JOIN sysjobs ON sysjobhistory.job_id = sysjobs.job_id
WHERE sysjobhistory.run_status = 0
GROUP BY sysjobs.name) x
ON x.name = sj.name
WHERE run_status = 1
GROUP BY sj.job_id, sj.name, last_Unsuccesful_run
dropped the status case bc it's clear enough this way. the case was not mandatory.

Related

How to exclude duplicate values / NULL values SQL

I hope that someone from you will be able to help me as I got stuck with a (silly) condition logic.
I am joining 2 temp tables.
The target is to see the Jobs, Tracking numbers, etc. (all actions) in one row always for one Consignee (Consignee Ref). In other words, to show all actions/data per Consignee Ref.
The issue I got is duplacated values. The problem is that the Original Job (620X) field can have assigned Tracking_1 but it can be also null. Also the Second Job (629X) filed can have but do not need to have assigned the Tracking number/value. It can be also the case that both Tracking_1 and Tracking are NULL for one Consignee Ref.
When I would exclude Jobs where Tracking_1 or Tracking is NULL, then I will loose the Jobs that have no Tracking Numbers at all. So I used the code below, but then I am getting duplicates.
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc
How can I make it that I will get rid of the unnecessary duplicates (an example marked in red)?
And at the same time not to loose those jobs that have no Tracking Numbers?
I hope it makes sense.
Thank you very much in advance for any advise!
This is the entire code:
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp;
SELECT distinct
cne.[Consignee Ref],
s.[Trial AWB] as [Original Job (620X)],
rl.[CarrierReference] as [Tracking_1],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]
into #Temp
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
LEFT JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id
WHERE [Clientaccountcode] in ('US429', 'MI1091')
--AND rl.[CarrierReference] is not null
-------------------------------------------
IF OBJECT_ID('tempdb..#Temp2') IS NOT NULL
DROP TABLE #Temp2;
SELECT distinct
cne.[Consignee Ref],
s.[Study Number] as [Study_],
s.[Site Number] as [Site No_],
s.[Trial AWB] as [Second (629X)],
rl.[CarrierReference] as [Tracking],
CAST(st.[Sched Collection date] as date) AS [Collection Date],
CAST(st.[Act Del Date] as date) AS [Delivery Date],
s.[Clientaccountcode] as [Account Code]
into #Temp2
FROM MKN_Reporting.dbo.shipment AS s WITH (NOLOCK)
LEFT JOIN MKN_Reporting.dbo.[Lookup Month By JN Tb] AS b WITH (NOLOCK) ON s.[id] = b.[JobId]
LEFT JOIN MKN_Reporting.dbo.[Lookup Branch currency Tb] AS c WITH (NOLOCK) ON b.BranchPrefix = c.[Branch Prefix]
LEFT JOIN MKN_Reporting.dbo.[Lookup Client group Tb] AS g WITH (NOLOCK) ON s.[Clientaccountcode] = g.[Customer A/c]
LEFT JOIN MKN_Reporting.dbo.[Chargeto] AS cg WITH (NOLOCK) ON s.[id] = cg.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Shipper] AS sh WITH (NOLOCK) ON s.[id] = sh.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Cnee] AS cne WITH (NOLOCK) ON s.[id] = cne.[jobid]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS r WITH (NOLOCK) ON sh.[Shipper Country code] = r.[Country Code]
LEFT JOIN MKN_Reporting.dbo.[Lookup Country & Region Tb] AS reg WITH (NOLOCK) ON cne.[Consignee Country code] = reg.[Country Code]
INNER JOIN MKN_Reporting.dbo.[Status] st ON COALESCE(s.ParentId, s.id) = st.Jobid
LEFT JOIN [CARRIERS_CHARGES] AS cc ON s.id = cc.JobId
left JOIN [RouteLegs] as rl on cc.RouteLegId = rl.id
WHERE [Clientaccountcode] in ('US1598')
--AND rl.[CarrierReference] is not null
---------------------------------------------
SELECT * FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
ORDER BY [Original Job (620X)] asc
I guess OP is looking for some kind of field aggregation for T2.
With SQL Server 2017+, like in PostgreSQL, you can now use STRING_AGG (same syntax than the Oracle LISTAGG.. "Why did they not use the same keyword...").
STRING_AGG will ignore null values from T2 and requires grouping if not alone. You have to add the other T1 and T2 required fields if any, but take care for T2 that it can imply duplicates and may need aggregation too...
Here is an example with your provided TSQL :
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
STRING_AGG(t2.[Tracking],',') WITHIN GROUP (ORDER BY t2.[Tracking] ASC) Tracking_T2
FROM #Temp t1
INNER JOIN #Temp2 t2 on t1.[Consignee Ref] = t2.[Consignee Ref]
WHERE t1.[Tracking_1] is not null
GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
ORDER BY t1.[Original Job (620X)] asc
EDIT: For previous SQL Server release (before 2017), you can achieve string aggregation with XML query :
EDIT2: Adding EXISTS clause to convey the INNER JOIN from the initial query.
SELECT t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1],
STUFF((SELECT ', ' + t2.[Tracking]
FROM #Temp2 t2
WHERE t1.[Consignee Ref] = t2.[Consignee Ref]
ORDER BY t2.[Tracking]
FOR XML PATH('')), 1, 1, N'') Tracking_T2
FROM #Temp t1
WHERE t1.[Tracking_1] is not null
AND EXISTS (SELECT DISTINCT 1 FROM #Temp2 t2 WHERE t2.[Consignee Ref] = t1.[Consignee Ref])
GROUP BY t1.[Consignee Ref], t1.[Original Job (620X)], t1.[Tracking_1]
ORDER BY t1.[Original Job (620X)] asc

Multiplying 2 columns in sql but calculation is incorrect?

I have the following select statement:
SELECT c.compname AS [Company]
,e.empname AS [Employee Name]
,a.jobid AS [Job Number]
,a.JobNavn AS [Job Name]
,t.TName [Task Name]
,cu.DayDate AS [Booking Date]
,cu.HrsBooked AS [Scheduled Hours]
,x.Ressnavn AS [Client]
,tr.Sale
,SUM(cu.HrsBooked) * (tr.Sale) AS [Total]
FROM job a
INNER JOIN jobplan jp ON jp.JobId = a.jobid
INNER JOIN JobDimensions AS z ON z.jobid = a.jobid
INNER JOIN Ress AS x ON x.RessId = z.custid
INNER JOIN JobPrice AS y ON y.JobId = a.Jobid
INNER JOIN task t ON t.PlanId = jp.PlanId
INNER JOIN JobPriceactivity AS w ON w.priceId = y.priceId
INNER JOIN taskres tr ON tr.TaskId = t.TaskId
INNER JOIN emp e ON e.EmpId = tr.ResId
INNER JOIN comp c ON e.compid = c.compid
INNER JOIN CapUsed AS cu ON cu.RefId = tr.TaskResId
AND cu.RefType = 1
INNER JOIN arpaccount AS ar ON e.empname = ar.arpaccname
AND CAST(cu.DayDate AS DATE) BETWEEN #startdate
AND #enddate
WHERE e.EMPID >= '2'
AND cu.HrsBooked > '0'
GROUP BY c.compname
,e.empname
,a.jobid
,a.JobNavn
,t.TName
,cu.DayDate
,cu.HrsBooked
,x.Ressnavn
,y.priceid
,tr.Sale
But the calculation of my 'SUM' in the select is not correct as highlighted in yellow in the following extract
I was expecting something like the below highlighted in green:
Can anyone highlight where I am going wrong either in my main code or column sum?

Unexplainable SQL behaviour

I have a simple SQL query, with a handful of joined queries.
In my select I have a function shaping the date to a string format as below
LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
The script I am running should return 84 rows currently, but when executing the above in the select, it continuosly returns a different volume of rows every execution? there are no changes to the underlying tables between executions.
The strange thing is that whe I swith this back to a standard date conversion, the rows total 84
CONVERT(DATETIME,CONVERT(NVARCHAR,ADM_DT)+' '+ADM_TM)
Can anyone explain why SQL is behaving this way, I have not seen this before?
Full script below:
SELECT
[Visit ID] = a050.HSP_NO
,[Current Site] = currwd.HOSP
,[Current Specialty] = curr.SPEC
,[Current Ward] = currwd.WARD
,[Current Ward Name] = REPLACE(currwd.CURRDESC,'"','')
,[Current Consultant] = curr.PROF
,[Admission Date] = LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
,[Active] = '1'
,[PAS ID] = [crn].[crn]
,[Patient Class] = 'IP'
,NHS.[nhsno]
,CHI.CHI
,CASE WHEN OSV.X_CN IS NOT NULL THEN 'OSV' ELSE '' END OSV
,CASE WHEN NHS.[nhsno] LIKE '7%' THEN '7 NHSNO' ELSE '' END [PROBLEM NHS NO]
,DATEDIFF(D,PATS.DATE_OF_BIRTH,CONVERT(DATE,ADM_DT)) /365 [AGE ON ADMISSION]
FROM PCSSSA..SILVER.APK050_HPROVSPELL a050 WITH (NOLOCK)
-- Current Admission details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, SPEC, PROF --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)curr
ON curr.X_CN = a050.X_CN
AND a050.HSP_NO = curr.HSP_NO
AND curr.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO DESC)
-- Current Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN, CEP_NO ORDER BY WS_NO DESC) AS WR
FROM PCSSSA..SILVER.APK052_WARDSTAY wdstay WITH (NOLOCK)
LEFT JOIN (SELECT
CURRWARD = OBJ_LOC,
CURRDESC = OBJ_DESC
FROM [PCSSSA]..[SILVER].[ENV030_LOCDETS] WITH (NOLOCK)
WHERE OBJ_TYPE = 'WARD'
AND DATE_TO IS NULL
)wdname
ON wdstay.WARD = wdname.CURRWARD
) currwd
ON curr.X_CN = currwd.X_CN
AND curr.CEP_NO = currwd.CEP_NO
AND currwd.WR=1
--- Admitting details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, PROF, SPEC --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)adm
ON adm.X_CN = a050.X_CN AND a050.HSP_NO = adm.HSP_NO
AND adm.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO)
-- Admitting Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN,CEP_NO ORDER BY WS_NO) AS WR FROM PCSSSA..SILVER.APK052_WARDSTAY WITH (NOLOCK)) admwd
ON adm.X_CN = admwd.X_CN
AND adm.CEP_NO = admwd.CEP_NO
AND admwd.WR=1
-- Patient Detail
LEFT JOIN
(SELECT
[id].[RM_PATIENT_NO],
[id].[NUM_ID_TYPE] + CONVERT(NVARCHAR,[NUMBER_ID]) [crn]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('0', '1', 'W')
)[crn]
ON a050.[X_CN] = [crn].[RM_PATIENT_NO]
-- NHS NUMBERS
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [nhsno]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] = ('NHS')
)NHS
ON NHS.RM_PATIENT_NO = a050.X_CN
-- CHI NUMBER
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [CHI]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('CHI')
)CHI
ON CHI.RM_PATIENT_NO = a050.X_CN
-- OVERSEES STATUS
LEFT JOIN
(
SELECT X_CN, [STATUS], SDATE, EDATE FROM PCSSSA..SILVER.CRS037_OSV_STATUS WITH (NOLOCK)
)OSV
ON OSV.X_CN = a050.X_CN
AND CONVERT(DATE,ADM_DT) >= OSV.SDATE
AND (OSV.SDATE IS NULL
OR CONVERT(DATE,ADM_DT) <= OSV.EDATE)
-- DEMOGRAPHICS
LEFT JOIN
(
SELECT RM_PATIENT_NO, DATE_OF_BIRTH FROM PCSSSA..[SILVER].[PATIENTS] WITH (NOLOCK)
)PATS
ON PATS.RM_PATIENT_NO = a050.X_CN
-- CURRENTLY ADMITTED ONLY
WHERE DIS_DT IS NULL
-- WITHOUT NHS NUMBER
AND (nhsno IS NULL
-- OR BRING IN ANY 7 NHS NUMBERS FOR CORRECTION
OR NHS.[nhsno] LIKE '7%'
-- ALSO INCLUDE OVERSEES
OR OSV.X_CN IS NOT NULL)
What is even stranger, is that if you wrap this in a subquery and coun(*) on the outer then it totals 84 as expected, very strange!

How to pick Max value of SQL Output

SQL Query Syntax issue. I have a query which returns around 150,000 rows of records. In this query, you can see ROW_NUMBER() OVER PARTITION. On select * from cte, I need to pick only the highest value of ROW_NUMBER() for each Pat_id.
If RowNumber is 150 for one pat_id. I need only that row of records. I am having difficult in narrowing down to one record. I request experts to share your syntax to help me.
with cte
as (
select pat.pat_id,
pat.fname as [FirstName],
pat.mname as [MiddleName],
pat.lname as [LastName],
[DOB] =Convert(VARCHAR(12),pat.birth_date,101),
csc.name as [AccountType],
[Plan Name] = CASE when (isnull(org.name,'')='') then 'CASH' else org.name end
,cprx_disp.disp_days_supply
,cprx_disp.dispense_date
,(cprx_disp.dispense_date + cprx_disp.disp_days_supply) as [DateDue]
,ROW_NUMBER() over(PARTITION BY pat.pat_id ORDER BY cprx_disp.dispense_date) as [RowNumber]
From cppat pat (nolock)
left outer join cppat_ins patins(NoLock) ON patins.pat_id = pat.pat_id
left outer join csorg org on org.org_id = patins.org_id
inner join csct_code csc on pat.pat_type_cn = csc.code_num
join cprx on cprx.pat_id = pat.pat_id
join cprx_disp (nolock) on cprx.last_rxdisp_id = cprx_disp.rxdisp_id
where csc.ct_id = 163
and csc.code_num in (1033,1010,1011,1012,1016,1017,1016,1018)
and patins.status_cn = 1
and patins.priority = 1
-- Commented.
-- and pat.pat_id = 2561
)
select cte.[FirstName],
cte.[MiddleName],
cte.[LastName],
cte.[DOB],
cte.[AccountType],
cte.[Plan Name],
Cte.DateDue
from cte
Well, you're not actually using the RowNumber in the output, so I would just reverse it and then return those that equal 1:
with cte
as (
select pat.pat_id,
pat.fname as [FirstName],
pat.mname as [MiddleName],
pat.lname as [LastName],
[DOB] =Convert(VARCHAR(12),pat.birth_date,101),
csc.name as [AccountType],
[Plan Name] = CASE when (isnull(org.name,'')='') then 'CASH' else org.name end
,cprx_disp.disp_days_supply
,cprx_disp.dispense_date
,(cprx_disp.dispense_date + cprx_disp.disp_days_supply) as [DateDue]
,ROW_NUMBER() over(PARTITION BY pat.pat_id ORDER BY cprx_disp.dispense_date DESC) as [RowNumber]
from cppat pat (nolock)
left outer join cppat_ins patins(NoLock) on patins.pat_id = pat.pat_id
left outer join csorg org on org.org_id = patins.org_id
inner join csct_code csc on pat.pat_type_cn = csc.code_num
join cprx on cprx.pat_id = pat.pat_id
join cprx_disp (nolock) on cprx.last_rxdisp_id = cprx_disp.rxdisp_id
where csc.ct_id = 163
and csc.code_num in (1033,1010,1011,1012,1016,1017,1016,1018)
and patins.status_cn = 1
and patins.priority = 1
-- Commented.
-- and pat.pat_id = 2561
)
select cte.[FirstName],
cte.[MiddleName],
cte.[LastName],
cte.[DOB],
cte.[AccountType],
cte.[Plan Name],
cte.DateDue
from cte
WHERE RowNumber = 1;

Calculate difference between two columns sql

in my SQL Query i am Calculating column values by using CASE WHEN THEN ELSE END Condition.
Now i want to find difference between computed column and normal column
My Query
SELECT T.Ticket [Ticket],
TT.TicketType [Ticket Type],
T.Dependency [Dependency],
CASE
WHEN (
SELECT TOP 1 f1.UpdatedOn
FROM TicketTypeFollowUp AS f1
WHERE f1.UpdatedOn < T.UpdatedOn
AND f1.Ticket = 61423
ORDER BY f1.UpdatedOn DESC
) IS NULL
THEN Ticket.TicketRaisedOn
ELSE (
SELECT TOP 1 f1.UpdatedOn
FROM TicketTypeFollowUp AS f1
WHERE f1.UpdatedOn < T.UpdatedOn
AND f1.Ticket = 61423
ORDER BY f1.UpdatedOn DESC
)
END [Start Date],
T.UpdatedOn [End Date],
L.EmpName [Updated By]
FROM dbo.TicketTypeFollowUp T
LEFT JOIN dbo.Ticket
ON T.Ticket = Ticket.Code
LEFT JOIN dbo.TicketType TT
ON T.TicketType = TT.Code
LEFT JOIN LoginUser L
ON T.UpdatedBy = L.Code
WHERE Ticket = 61423
Query Result
Ticket Type Dependency Start Date End Date Updated By
61423 FLM AGS 2013-01-22 15:50:08.757 2013-01-22 18:35:50.893 Kedar S
I want one more column which displays End Time - Start Time I have used CASE hence i am unable to compute difference.
Database is SQL SERVER 2008
with lastUpdate(ticket, lastUpdate) as (
select ticket,
max(updateOn)
from TicketTypeFollowUp
group by ticket)
SELECT T.Ticket [Ticket],
TT.TicketType [Ticket Type],
T.Dependency [Dependency],
coalesce(lastUpdate, ticketRaisedOn) [Start Date],
T.UpdatedOn [End Date],
datediff(mi, coalesce(lastUpdate, ticketRaisedOn), T.UpdatedOn) durationMins,
L.EmpName [Updated By]
FROM dbo.TicketTypeFollowUp T
LEFT JOIN dbo.Ticket
ON T.Ticket = Ticket.Code
LEFT JOIN dbo.TicketType TT
ON T.TicketType = TT.Code
LEFT JOIN LoginUser L
ON T.UpdatedBy = L.Code
left join lastUpdate lu on t.ticket = lu.ticket
WHERE Ticket = 61423
You can use your current query as a CTE or a derived table. Here is an example using a CTE:
;WITH CTE AS
(
-- your current query here
)
SELECT *, DATEDIFF(MINUTE,[Start Date],[End Date]) [End Time - Start Time]
FROM CTE