I need to make a query that gets the the status of sql server agent jobs.
The tricky part, is that I both want the time the job last have failed (if any) AND when it last ran successful - is that possible?
So far I have only been able to get the last successful run or the last failed run of a job.
SELECT
job.name
,jobh.run_date
,DATEADD(HOUR, (jobh.run_time / 1000000) % 100,
DATEADD(MINUTE, (jobh.run_time / 10000) % 100,
DATEADD(SECOND, (jobh.run_time / 100) % 100,
DATEADD(MILLISECOND, (jobh.run_time % 100) * 10,
cast('00:00:00' as TIME(0)))))) AS 'tidspunkt'
,jobh.run_duration
FROM msdb.dbo.sysjobhistory jobh
JOIN [msdb].[dbo].[sysjobs] job ON jobh.job_id = job.job_id
WHERE jobh.step_id = 0
AND jobh.message LIKE '%failed%'
AND (jobh.run_date = CONVERT(VARCHAR, GETDATE(), 112) OR jobh.run_date = CONVERT(VARCHAR, DATEADD(DAY, -1, GETDATE()), 112) )
AND job.name = 'UpdateCPR'
ORDER BY jobh.run_date DESC, jobh.run_time DESC
Just change the line...
AND jobh.message LIKE '%failed%'
...to following...
AND (jobh.message LIKE '%failed%' OR jobh.message LIKE '%succeeded%')
You will get multiple rows. If you wish, you can group that by LIKE result and select TOP 1 from both to retrieve it in one row.
EDIT
Use this to get both fail and success info in one row.
;WITH jobRuns AS (
SELECT
job.job_id,
job.name,
jobh.run_time,
jobh.run_duration,
execStatus
FROM msdb.dbo.sysjobhistory jobh
JOIN msdb.dbo.sysjobs job
ON jobh.job_id = job.job_id
CROSS APPLY(
SELECT execStatus = CASE
WHEN jobh.message LIKE '%failed%' THEN 0
WHEN jobh.message LIKE '%succeeded%' THEN 1 END) ext
WHERE
jobh.step_id = 0
and job.name LIKE '%testjob%'
/*GROUP BY
job.job_id,
job.name,
jobh.run_time,
execStatus*/)
,lastRuns AS (
SELECT TOP 1
jobRuns.job_id,
jobRuns.name,
run_time_failed = failed.run_time,
run_duration_failed = failed.run_duration,
run_time_succeeded = success.run_time,
run_duration_succeeded = success.run_duration
FROM jobRuns
CROSS APPLY(
SELECT TOP 1 run_time, run_duration
FROM jobRuns
WHERE execStatus = 0
ORDER BY run_time DESC) failed
CROSS APPLY(
SELECT TOP 1 run_time, run_duration
FROM jobRuns
WHERE execStatus = 1
ORDER BY run_time DESC) success
)
SELECT *
FROM lastRuns
Related
i have an example data :
I need to get the count of SNs for the next 5 seconds where the SNs are of the same type and the same selection
I tried using join but didn't quite get to the point. Is there a way to get this.
select *
from TestData t1
cross apply
(
select
count(*) [Count],
isnull(string_agg(t2.SN, ','), '-') [Related SN]
from TestData t2
where
t2.SN <> t1.SN
and t2.Type = t1.Type
and t2.Selection = t1.Selection
and t2.DT >= t1.DT
and datediff(second, t1.DT, t2.DT) < 5
) RelatedSN;
My SQL query runs perfectly, but when I add the CTE function, I get an error
Please check this code and let me know what's wrong with the CTE:
WITH Consumption_details(UnitId, consumption, monthof, yearof) AS
(
SELECT
UnitId, SUM(consumption) AS consumption,
monthof, yearof
FROM
(SELECT
UnitId, apartment_consumption,
DATEPART(MONTH, day) AS monthof,
DATEPART(YEAR,day) AS yearof
FROM
MeterReading) AS t
GROUP BY
yearof, monthof, UnitId
HAVING
monthof = 2 AND yearof = 2022
ORDER BY
UnitID
)
You can't have ORDER BY inside the CTE (unless you also include TOP, which you shouldn't do in this case), and you need to do something with the CTE - it's just an expression, not a query on its own.
;;;/*be safe!*/;;;With cd(SonnenUnitId, consumption, monthof, yearof) AS
(
SELECT SonnenUnitId, ...
...
GROUP BY yearof, monthof, SonnenUnitId
HAVING monthof =2 and yearof =2022
)
SELECT * FROM cd Order by SonnenUnitID;
As an aside, this query could be a whole lot more efficient with no need for a CTE and a subquery, any of the HAVING, and the scan potentially becoming a seek.
DECLARE #mo int = 2, #yo int = 2022;
DECLARE #m date = DATEFROMPARTS(#yo, #mo, 1);
SELECT SonnenUnitId,
SUM(apartment_consumption) AS consumption,
monthof = #mo,
yearof = #yo
FROM dbo.SonnenMeterReading
WHERE [day] >= #m
AND [day] < DATEADD(MONTH, 1, #m)
GROUP BY SonnenUnitId
ORDER BY SonnenUnitId;
We have a table that stores a list of all the quotes we have sent out.
Anytime a customer revises the quotes, the system automatically appends a -1 or -2 based on last used number.
As an example
Original Quote Number : 24545
Customer asked for a revision, the quote number is now 24545-1, after sending the quote, we now have a revision again and the Quote is 24545-2 and so on.
I want to run a SQL query that will show them their Top 20 Quotes and incase of revisions, it should show the latest revisions.
Can you please help me?
I have already written a Query that would bring me top 20 quotes for the last 10 days.
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [Enterprise32].[dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() AND SalesRepCode = $id And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC
This makes some assumptions, but I think this might work. If not, sample data and expected result will be invaluable:
USE Enterprise32;
GO
WITH CTE AS(
SELECT V.EstimateNumber,
V.RevisionNumber,
TN1.CustName,
TN1.JobDescription,
TN1.TotalSellPrice,
TN1.EstimateStatus,
TN1.EstimateDate,
TN1.CommissionTableA,
ROW_NUMBER() OVER (PARTITION BY V.EstimateNumber ORDER BY V.RevisionNumber DESC) AS RN
FROM dbo.TableName1 TN1
CROSS APPLY (VALUES(NULLIF(CHARINDEX('-',TN1.EstimateNumber),0)))CI(I)
CROSS APPLY (VALUES(TRY_CONVERT(int,LEFT(TN1.EstimateNumber,ISNULL(CI.I,LEN(TN1.EstimateNumber))-1)),ISNULL(TRY_CONVERT(int,STUFF(TN1.EstimateNumber,1,CI.I,'')),0)))V(EstimateNumber,RevisionNumber)
WHERE TN1.EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE()
AND TN1.SalesRepCode = $id
And TN1.TotalSellPrice > '5000'
AND TN1.EstimateStatus = 'P')
SELECT TOP (20)
EstimateNumber,
RevisionNumber,
CustName,
JobDescription,
TotalSellPrice,
EstimateStatus,
EstimateDate,
CommissionTableA
FROM CTE
WHERE RN = 1;
With some minor changes, it might work, As there is no data sample:
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [dbo].[tablename1] tt
LEFT JOIN
(
--Top 20 quotes Last EstimateNumber with revision
SELECT T20.RevisionFree_EstimateNumber +
CONVERT(VARCHAR,
MAX(CONVERT(INT,
SUBSTRING(t.EstimateNumber, CHARINDEX('-', EstimateNumber)+1, LEN(EstimateNumber)-CHARINDEX('-', EstimateNumber))))) Last_EstimateNumber
FROM
(
--Top 20 quotes Original EstimateNumber
SELECT DISTINCT Top 20
TotalSellPrice
,SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC
)AS T20
LEFT JOIN
(
SELECT *, SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
) t
ON T20.RevisionFree_EstimateNumber = t.RevisionFree_EstimateNumber
GROUP BY T20.RevisionFree_EstimateNumber
)LastEN
ON tt.EstimateNumber = LastEN.Last_EstimateNumber
I need the output from this.. i know this is wrong it is just an example
SELECT
customer_name,
((Qty * 0.5), *
(CASE WHEN (DATEDIFF(month, Appointment_Date,getdate())) < 12 )'Incentive'
FROM t1,t2
WHERE t1.customer_code = t2.customer_code
I think you are looking for this:
select customer_name,((Qty * 0.5) *
(case when (datediff (month, Appointment_Date,getdate()) < 12 ) then
datediff (month, Appointment_Date,getdate()) else 1 end ) )'Incentive'
from t1,t2
where t1.customer_code = t2.customer_code
As far as I understand from your comments (please read introductory notes on how to post on S.O.), maybe you can use a query like this.
I changed your original query using JOIN clause too.
SELECT
customer_name,
Qty * 0.5 *DATEDIFF(month, Appointment_Date,getdate()) AS INCENTIVE
FROM t1
INNER JOIN t2 ON t1.customer_code = t2.customer_code
WHERE DATEDIFF(month, Appointment_Date,getdate()) < 12
I want to report a script which contains a Select from(Select) , when I just run the second Select I have no problem but When I put the hole script it loads and nothing happen.
Here's my code :
SELECT top 100 *,
CASE
WHEN Frequency='1'
AND DATEDIFF(HOUR, T.MeasurementDate, T.nextMeasurement) > 1 THEN 'Missing Hour(s)'
WHEN Frequency='1'
AND T.MeasurementDate = T.maxMeasurement
AND DATEDIFF(HOUR, T.maxMeasurement, CONVERT(DATE, #EndDate)) > 1 THEN 'Missing Max Hour(s)'
WHEN Frequency='2'
AND DATEDIFF(DAY, T.MeasurementDate, T.nextMeasurement) > 1 THEN 'Missing Day(s)'
WHEN Frequency='2'
AND T.MeasurementDate = T.maxMeasurement
AND DATEDIFF(DAY, T.maxMeasurement, CONVERT(DATE, #EndDate)) > 1 THEN 'Missing Max Day(s)'
ELSE 'OK'
END AS [Verification] INTO #tt FROM
(SELECT top 100 Flow.Id AS idFlow, Flow.ComponentId, Flow.Frequency, pip.Name AS PipelineName, LEAD(Flow.MeasurementDate) OVER (Partition BY ComponentId, NominationCycle, LocationType, Frequency, FlowTypeId, UnitofMeasurement
ORDER BY MeasurementDate) nextMeasurement, MAX(Flow.MeasurementDate) OVER (PARTITION BY ComponentId, NominationCycle, LocationType, Frequency, FlowTypeId, UnitofMeasurement) maxMeasurement
FROM BentekDatabase.dbo.Flow Flow
INNER JOIN BentekDatabase.dbo.Pipeline pip ON Flow.PipelineId = pip.id
WHERE ScheduledVolume IS NOT NULL
AND MeasurementDate BETWEEN #StartDate AND #EndDate) AS T
SELECT COUNT (*)
FROM #tt
WHERE Verification != 'OK'
PS : The code run perfectly in SSMs when I declare values for 2 parameter.
I want to display the result of the last query ( select count (*) from #tt where Verification != 'OK') in a new page report results, which will contain the result of all my other queries too.
ANy Idea ?