Trying to convert this SQL query to athena query - sql

Trying to convert this to Athena query special the case statement bit
select
RegDate,
COALESCE(cast(convert(varchar(7), RegDate, 126) as varchar(7)), NULL ) as [RegMonthYear]
,DATEPART(month, RegDate) as RegMonth
,DATEPART(year, RegDate) as RegYear
,code
,case
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end < '20'+code+'01'
then 'Jan'
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end > '20'+code+'12'
then 'Dec'
else Convert(char(3), RegDate,0)
end EditionMonth
,case
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar) end < '20'+code+'01' then 1
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end > '20'+code+'12' then 12
else DATEPART(m,RegDate)
end EditionMonthNumber
from Details

Related

Getting number from place value in sql

I have a form set up that has Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday. When populated into the SQL database it starts off with 7 0s, each 0 representing the day of the week and when a day of the week is selected a 1 in the correct place. For instance if Monday is selected the value would be 1000000, if Tuesday 010000, Wednesday 001000 etc. Users have the option to select multiple days so it could be 101000 for Monday and Wednesday or 1111111 for all days. What would be the best route to convert this into a sql query to say if the 1 is in the hundred thousands place that equals Monday and if the 1 is in 101000 the value is Monday and Wednesday?
Let me know, thanks!
If 2012+ You can use concat(). Also included STUFF() for a "cleaner" string.
Example
Declare #YourTable table (SomeCol varchar(25))
Insert Into #YourTable values
('1000000'),
('1100000'),
('0100000'),
('1111111')
Select *
,NewCol = stuff(
concat(
', '+IIF(substring(SomeCol,1,1)='1','Monday' ,null)
,', '+IIF(substring(SomeCol,2,1)='1','Tuesday' ,null)
,', '+IIF(substring(SomeCol,3,1)='1','Wednesday',null)
,', '+IIF(substring(SomeCol,4,1)='1','Thursday' ,null)
,', '+IIF(substring(SomeCol,5,1)='1','Friday' ,null)
,', '+IIF(substring(SomeCol,6,1)='1','Saturday' ,null)
,', '+IIF(substring(SomeCol,7,1)='1','Sunday' ,null)
),1,2,'')
From #YourTable
Returns
SomeCol NewCol
1000000 Monday
1100000 Monday, Tuesday
0100000 Tuesday
1111111 Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
EDIT - For 2008
Declare #YourTable table (SomeCol varchar(25))
Insert Into #YourTable values
('1000000'),
('1100000'),
('0100000'),
('1111111')
Select *
,NewCol = stuff(
case when substring(SomeCol,1,1)='1' then ', Monday' else '' end
+case when substring(SomeCol,2,1)='1' then ', Tuesday' else '' end
+case when substring(SomeCol,3,1)='1' then ', Wednesday' else '' end
+case when substring(SomeCol,4,1)='1' then ', Thursday' else '' end
+case when substring(SomeCol,5,1)='1' then ', Friday' else '' end
+case when substring(SomeCol,6,1)='1' then ', Saturday' else '' end
+case when substring(SomeCol,7,1)='1' then ', Sunday' else '' end
,1,2,'')
From #YourTable
Sounds quite odd... but perhaps you are looking for something like this:
declare #var varchar(64) = '1010111'
select
isnull(case when left(#var,1) = 1 then 'Monday' end,'')
+ ' ' +
isnull(case when substring(#var,2,1) = 1 then 'Tuesday' end,'')
+ ' ' +
isnull(case when substring(#var,3,1) = 1 then 'Wednesday' end,'')
+ ' ' +
isnull(case when substring(#var,4,1) = 1 then 'Thursday' end,'')
+ ' ' +
isnull(case when substring(#var,5,1) = 1 then 'Friday' end,'')
+ ' ' +
isnull(case when substring(#var,6,1) = 1 then 'Saturday' end,'')
+ ' ' +
isnull(case when right(#var,1) = 1 then 'Sunday' end,'')

SQL - How to find currently running job steps through TSQL

I am writing a query to find currently running job in SQL (I know we can view it in Job Active Monitor, but I've a need to do in TSQL). Though I can query sysjobactivity table to find currently running job, it's nowhere telling what job step is running (because my job might have more than 1 step).
Query I used:
SELECT s.name AS [JOB_NAME],
'' AS [STEP_ID],
'' AS STEP_NAME,
'Processing' AS STATUS,
sja.run_requested_date AS START_TIME,
null AS END_DATE,
convert(varchar, (getdate() - sja.run_requested_date), 8) AS Duration
FROM sysjobactivity sja, sysjobs s
WHERE sja.job_id = s.job_id
AND sja.run_requested_date > getdate() - 1
AND sja.stop_execution_date IS NULL
Please help me finding the step ID & Step name in which the job is currently progressing.
I think below script help to get SQL Jobs with current execution step, try this
msdb.dbo.sp_help_job #execution_status = 1
DECLARE #StepCount INT
SELECT #StepCount = COUNT(1)
FROM msdb.dbo.sysjobsteps
WHERE job_id = '0523333-5C24-1526-8391-AA84749345666' --JobID
SELECT
[JobName]
,[JobStepID]
,[JobStepName]
,[JobStepStatus]
,[RunDateTime]
,[RunDuration]
FROM
(
SELECT
j.[name] AS [JobName]
,Jh.[step_id] AS [JobStepID]
,jh.[step_name] AS [JobStepName]
,CASE
WHEN jh.[run_status] = 0 THEN 'Failed'
WHEN jh.[run_status] = 1 THEN 'Succeeded'
WHEN jh.[run_status] = 2 THEN 'Retry (step only)'
WHEN jh.[run_status] = 3 THEN 'Canceled'
WHEN jh.[run_status] = 4 THEN 'In-progress message'
WHEN jh.[run_status] = 5 THEN 'Unknown'
ELSE 'N/A'
END AS [JobStepStatus]
,msdb.dbo.agent_datetime(run_date, run_time) AS [RunDateTime]
,CAST(jh.[run_duration]/10000 AS VARCHAR) + ':' + CAST(jh.[run_duration]/100%100 AS VARCHAR) + ':' + CAST(jh.[run_duration]%100 AS VARCHAR) AS [RunDuration]
,ROW_NUMBER() OVER
(
PARTITION BY jh.[run_date]
ORDER BY jh.[run_date] DESC, jh.[run_time] DESC
) AS [RowNumber]
FROM
msdb.[dbo].[sysjobhistory] jh
INNER JOIN msdb.[dbo].[sysjobs] j
ON jh.[job_id] = j.[job_id]
WHERE
j.[name] = 'ProcessCubes' --Job Name
AND jh.[step_id] > 0
AND CAST(RTRIM(run_date) AS DATE) = CAST(GETDATE() AS DATE) --Current Date
) A
WHERE
[RowNumber] <= #StepCount
AND [JobStepStatus] = 'Failed'
Try this:
SELECT distinct
cast([sJOB].[job_id] as varchar(max)) AS execution_id
, [sJSTP].[step_name] AS executable_name
, [sJOB].[name] AS package_name
, CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS start_time,
dateadd(ss, run_duration, CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END) end_time
-- , [sJSTP].[run_duration] [looptijd in minuten]
, CASE [sJSTP].[run_status]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Success'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Cancelled'
WHEN 5 THEN 'Unknown'
END AS execution_result_description
FROM
[msdb].[dbo].[sysjobhistory] AS [sJSTP]
INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB]
ON [sJSTP].[job_id] = [sJOB].[job_id]
inner join [msdb].[dbo].[sysjobsteps] steps
ON [sJSTP].[job_id] = [steps].[job_id]
where [sJSTP].[run_date] <> 0
and CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END between dateadd(hh, -20, getdate()) and getdate()
and [sJSTP].[step_name] not in ('(Job outcome)')
order by start_time desc
Additionally I use this query to see step result from a running SSIS job. However, this only shows you the finished steps, not the running ones. I still have to find an SQL to see the currently running step and merge it with this one.
select distinct
cast(e.execution_id as varchar(max)),
e.executable_name,
e.package_name,
CONVERT(datetime, es.start_time) AS start_time
, CONVERT(datetime, es.end_time) AS end_time
, datediff(mi, es.start_time, es.end_time) [running time]
, case es.execution_result
when 0 then 'Success'
when 1 then 'Failed'
when 2 then 'Completion'
when 3 then 'Cancelled'
else cast(es.execution_result as varchar(max)) end as execution_result_description
from ssisdb.catalog.executables e
left join ssisdb.catalog.executable_statistics es
on e.executable_id = es.executable_id
and e.execution_id = es.execution_id
order by 6 desc

In IF statement with dates see whether a NULL exists

I have this query and i see if the AUD_CloseDate is > than todays date. Now i imagine these would be a NULL somewhere in AUD_CloseDate so in this statement i also want to check if there is a NULL value in AUD_CloseDate and if there is assign value 1900\01\01
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_CloseDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER
COALESCE is ANSI-compliant. Same syntax as ISNULL: COALESCE(t2.AUD_CloseDate,'19000101')
Why about a ISNULL() statement ?
ISNULL(t2.AUD_CloseDate,'19000101')
In you example :
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,ISNULL(t2.AUD_CloseDate,'19000101')), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER
Use ISNULL function
ISNULL(AUD_CloseDate, '1900-01-01')
You are also:
adding 0 days to date
casting it to char(10)
, then casting again to date... Why?
You can achieve the same result withou these conversions, like this example:
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 13:50') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'Over due:'
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 15:00') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'On Time:'
** Now is 13:55 :)

How to improve this sql query

Here I get the "ProcessTime" in hours and minutes, but in case of seconds only I check for the opposite condition (see code below)
Is there any way to improve that?
select convert(varchar(10),ScanDate,101) as [Date], tmb.WO, tc.WOCategory, count(IdSingle) QtyProd, tb.Brand, tm.Model,
(case when (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24 > 0) then
convert(varchar(5), DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24) + 'h '
else
''
end) +
(case when (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60 > 0) then
convert(varchar(5), DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60) + 'm'
else
''
end) +
(case when
(DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24 <= 0) and
(DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60 <= 0) then
'< 1 min'
else
''
end) ProcessTime
With SQL Server 2005 you can use a CTE to improve this query.
Something like this:
;WITH minmax AS
(
SELECT someKey,
DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8))) as mdiff
FROM tablename
GROUP BY fieldName
)
Select convert(varchar(10),ScanDate,101) as [Date], tmb.WO, tc.WOCategory, count(IdSingle) QtyProd, tb.Brand, tm.Model,
(case when (mdiff/60%24 > 0) then
convert(varchar(5), mdiff/60%24) + 'h '
else
''
end) +
(case when (mdiff%60 > 0) then
convert(varchar(5), mdiff%60) + 'm'
else
''
end) +
(case when
(DateDiff(mi, mdiff/60%24 <= 0) and (DateDiff(mi, mdiff%60 <= 0) then
'< 1 min'
else
''
end) ProcessTime
from tablename
join minmax on tablename.somekey = minmax.somekey

Getting date string from getdate method

I need date string using sql statement like..
select getDate()
this will return 2010-06-08 16:31:47.667
but I need in this format 201006081631 = yyyymmddhoursmin
How can I get this?
Thanks
One way
select left(replace(replace(replace(
convert(varchar(30),getDate(),120),' ',''),'-',''),':',''),12)
or like this
select replace(replace(replace(
convert(varchar(16),getDate(),120),' ',''),'-',''),':','')
or
select convert(varchar(8), getdate(),112) +
(replace(convert(varchar(5), getdate(),108),':',''))
See also: CAST and CONVERT (Transact-SQL)
Another way...
DECLARE #d DATETIME
SELECT #d = '2010-06-09 1:37:58.030'
Select Convert(BigInt, 100000000) * Year(#d)
+ Month(#d) * 1000000
+ Day(#d) * 10000
+ DatePart(Hour, #d) * 100
+ DatePart(Minute, #d)
The returned data type here is a BigInt.
Using DATEPART:
SELECT CAST(DATEPART(yyyy, x.dt) AS VARCHAR(4)) +
CASE WHEN DATEPART(mm, x.dt) < 10 THEN '0'+ CAST(DATEPART(mm, x.dt) AS VARCHAR(1)) ELSE CAST(DATEPART(mm, x.dt) AS VARCHAR(2)) END +
CASE WHEN DATEPART(dd, x.dt) < 10 THEN '0'+ CAST(DATEPART(dd, x.dt) AS VARCHAR(1)) ELSE CAST(DATEPART(dd, x.dt) AS VARCHAR(2)) END +
CASE WHEN DATEPART(hh, x.dt) < 10 THEN '0'+ CAST(DATEPART(hh, x.dt) AS VARCHAR(1)) ELSE CAST(DATEPART(hh, x.dt) AS VARCHAR(2)) END +
CASE WHEN DATEPART(mi, x.dt) < 10 THEN '0'+ CAST(DATEPART(mi, x.dt) AS VARCHAR(1)) ELSE CAST(DATEPART(mi, x.dt) AS VARCHAR(2)) END
FROM (SELECT '2010-06-08 16:31:47.667' dt) x
For SQL Server 2005+, I'd look at creating a CLR function for format a date -- the C# DateTime.ToString() supports providing a more normal means of formatting the date.