I am pulling in certain data and would like to reduce my code by having SQL do all the work for me in a Stored Procedure. It is currently pulling in many records, but if it does what I want then it will only yield a single line of results. Below is my Stored Procedure:ALTER PROCEDURE dbo.spGetTPHCurrentPipe @shiftStart DATETIME = NULLAS BEGIN SELECT dtTimeStamp, PipeGauge, PipeDiameter, PipeWeight FROM tblPipeCount WHERE (PipeGauge = (SELECT PipeGauge FROM tblPipeCount WHERE dtTimeStamp = (SELECT TOP(1)dtTimeStamp FROM tblPipeCount ORDER BY dtTimeStamp DESC))) AND (PipeDiameter = (SELECT PipeDiameter FROM tblPipeCount WHERE dtTimeStamp = (SELECT TOP(1)dtTimeStamp FROM tblPipeCount ORDER BY dtTimeStamp DESC))) AND dtTimeStamp BETWEEN @shiftStart AND getdate() ORDER BY dtTimeStamp ASC END RETURN
I know it isn't the cleanest looking code, but it gets the job done. If you noticed, the 'PipeGauge' and 'PipeDiameter' columns will be the exact same data for every record pulled. The only data that will be different is the 'dtTimeStamp' and 'PipeWeight'. Also, as you can see this will be ordered by the 'dtTimeStamp' column too. Is there any way to return the following:SELECT DATEDIFF(FIRST_RECORD_dtTimeStamp,LAST_RECORD_dtTimeStamp), PipeGauge, PipeDiameter, SUM(PipeWeight) / 2000 AS PipeData
I am not very good with SQL and I hope this will just help give an idea of what I am trying to accomplish. The TimeSpan between the first and last record of 'dtTimeStamp', the 'PipeGauge', the 'PipeDiameter', and the sum of all the pipe weights divided by 2000. Is this possible, can anyone help me?