SQL User Defined Functions (UDE'S)
Create a function named SumRideHrsSingleDay()
which returns the total ride time in hours for the @DateParm
parameter passed.
- Create SumRideHrsSingleDay
CREATE FUNCTION SumRideHrsSingleDay (@DateParm date)
-- Specify return data type
RETURNS numeric
AS
-- Begin
BEGIN
RETURN
-- Add the difference between StartDate and EndDate
(SELECT SUM(DATEDIFF(second, StartDate, EndDate))/3600
FROM CapitalBikeShare
-- Only include transactions where StartDate = @DateParm
WHERE CAST(StartDate AS date) = @DateParm)
-- End
END
2. Often times you will need to pass more than one parameter to a function. Create a function that accepts @StartDateParm
and @EndDateParm
and returns the total ride hours for all transactions that have a StartDate
within the parameter values.
CREATE FUNCTION SumRideHrsDateRange (@StartDateParm datetime,@EndDateParm datetime)
-- Specify return data type
RETURNS numeric
AS
BEGIN
RETURN
-- Sum the difference between StartDate and EndDate
(SELECT SUM(DATEDIFF(second, StartDate, EndDate))/3600
FROM CapitalBikeShare
-- Include only the relevant transactions
WHERE StartDate > @StartDateParm and StartDate < @EndDateParm)
END
ITVF
CREATE FUNCTION SumStationStats(@StartDate AS datetime)
-- Specify return data type
RETURNS TABLE
AS
RETURN
SELECT
StartStation,
-- Use COUNT() to select RideCount
COUNT(ID) AS RideCount,
-- Use SUM() to calculate TotalDuration
SUM(Duration) AS TotalDuration
FROM CapitalBikeShare
WHERE CAST(StartDate as Date) = @StartDate
-- Group by StartStation
GROUP BY StartStation;
Comments
Post a Comment