My table consist of columns StartTime and EndTime with datetime datatype. I have calculated the duration from this two columns using this query:
SELECT
StartTime, EndTime,
DATEDIFF(s, StartTime, EndTime) AS duration
FROM tbl_record
WHERE StartTime >= @starttime AND StartTime < @endtime
ORDER BY StartTime DESC
How can I calculate the total sum of duration in sql query. This can be done using script but how to do in the database query? I have added something like
SELECT SUM(duration) as total
Shows error:
duration invalid column
You can’t use an alias like that. You either have to use your original calculation in the sum and alias that as
durationor use your original statement as a subselect to be able to use the
durationalias in the outer select.