I'm trying to get data from the Jira DB (SQL Server ie. MSSQL), so I can tell how long a time was spend in a given case status.
As you all might know that information is provided in the Jira interface by a plugin and not as a stored value in the DB.
I found an Oracle SQL script online, which I then converted to a MSSQL script to the best of my ability.. which it seems is a bit lacking, considering that I'm not used to MSSQL.
The script (below) gives me no result. I've narrowed it down to an issue with one of the last JOINS ie.
JOIN events e2 ON e1.NG =e2.NG AND e1.myrank=e2.myrank+1
Where the script re-joins EVENTS with itself to be able to get two rows (the two execution times that needs to be subtracted to get time spend in a status)
Any help or suggestion will be very welcome.. this is driving me nuts 
Note: the whole point is to use the script in MS PowerBI.
WITH core AS
(select
jiraissue.pkey NG,
convert(varchar, jiraissue.project) project,
SUBSTRING(changeitem.oldstring,4000,1) step,
changegroup.created Executed
from changeitem
join changegroup
on
changeitem.groupid = changegroup.id
join jiraissue
on
jiraissue.id = changegroup.issueid
where
changeitem.field ='status'
),
EVENTS AS
(SELECT
tab.*,
row_number() over(PARTITION BY NG ORDER BY executed) myrank
FROM
(SELECT * FROM core
UNION ALL
SELECT jiraissue.pKEY,
convert(varchar, jiraissue.project),
'Ticket Created',
jiraissue.created
FROM jiraissue
WHERE
jiraissue.pKEY IN (SELECT NG FROM core)
UNION ALL
SELECT DISTINCT NG, project, 'Terminal', getdate() FROM core
) tab
)
SELECT
e2.NG,
project.pkey project_key,
e2.step,
e2.executed,
round(24*60*(convert(int,e1.executed)-convert(int,e2.executed)),0) transition_time_min
FROM EVENTS e1
JOIN events e2
ON
e1.NG =e2.NG AND e1.myrank=e2.myrank+1
JOIN project
ON
e1.project = project.id