Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sql query to create graph from a table of events

I have a plain old table in SQL Server like so:

JOB    Step     Timestamp
----------------------------------
1      begin    12/25/2021 1:00 AM
1      foo      12/25/2021 1:01 AM
1      bar      12/25/2021 1:02 AM
1      end      12/25/2021 1:03 AM

It is a list of steps, that transition from one to the other, and the transition is determined by the timestamp. I would like to render it as a graph of events, so am trying to query it with results like:

JOB    Source    Target   Timestamp
--------------------------------------------
1      begin     foo      12/25/2021 1:01 AM
1      foo       bar      12/25/2021 1:02 AM  
1      bar       end      12/25/2021 1:03 AM

This is not a SQL Server graph table but I’d like it to behave like one in this case.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is ultimately going to be rendered in PowerBI using a force directed graph visualization, so answers in T-SQL or DAX would work for my use case.

>Solution :

In t-sql this is simple with lead() window function, the following should produce your expected results

select JOB, [Source], [Target], [TimeStamp]
from (
    select JOB, Step [Source],
        Lead(Step) over(partition by JOB order by [Timestamp]) [Target],
        Lead([Timestamp]) over(partition by JOB order by [Timestamp]) [TimeStamp]
    from t
)t
where [Target] is not null;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading