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;














Multi Statement TVF

CREATE FUNCTION CountTripAvgDuration (@Month CHAR(2), @Year CHAR(4))
-- Specify return variable
RETURNS @DailyTripStats TABLE(
TripDate date,
TripCount int,
AvgDuration numeric)
AS
BEGIN
-- Insert query results into @DailyTripStats
INSERT @DailyTripStats
SELECT
    -- Cast StartDate as a date
CAST(StartDate AS date),
    COUNT(ID),
    AVG(Duration)
FROM CapitalBikeShare
WHERE
DATEPART(month, StartDate) = @Month AND
    DATEPART(year, StartDate) = @Year
-- Group by StartDate as a date
GROUP BY CAST(StartDate AS date)
-- Return
RETURN
END

Comments

Popular posts from this blog

Binomial Test in Python

Slicing and Indexing in Python Pandas

Python Syntax and Functions Part2 (Summary Statistics)