Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Last active December 11, 2015 01:08
Show Gist options
  • Select an option

  • Save tugberkugurlu/4520825 to your computer and use it in GitHub Desktop.

Select an option

Save tugberkugurlu/4520825 to your computer and use it in GitHub Desktop.
Select the first and last log records for a request (Group by CorrelationId)
-- http://stackoverflow.com/questions/3800551/sql-select-first-row-in-each-group-by-group
-- http://dbaspot.com/sqlserver-programming/363437-union-two-ctes-together.html
-- http://stackoverflow.com/questions/354224/combining-union-all-and-order-by-in-firebird
WITH FirstLogs AS (
SELECT
l.[CorrelationId],
l.[Timestamp],
ROW_NUMBER() OVER(PARTITION BY l.[CorrelationId] ORDER BY l.[Timestamp] ASC) AS rk
FROM [DependencyScopeTracingDisposeBug.Models.Entities.WebApiTracerContext].[dbo].[HttpApiLogRecords] l
),
LastLogs AS (
SELECT
l.[CorrelationId],
l.[Timestamp],
ROW_NUMBER() OVER(PARTITION BY l.[CorrelationId] ORDER BY l.[Timestamp] DESC) AS rk
FROM [DependencyScopeTracingDisposeBug.Models.Entities.WebApiTracerContext].[dbo].[HttpApiLogRecords] l
)
SELECT * FROM (
SELECT fl.[CorrelationId], fl.[Timestamp] FROM FirstLogs fl WHERE fl.rk = 1
UNION ALL
SELECT ll.[CorrelationId], ll.[Timestamp] FROM LastLogs ll WHERE ll.rk = 1
) AS Logs
ORDER BY [CorrelationId];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment