create function udftobusinesshours(@datetime datetime) returns datetime as begin…
- User
create function udf_tobusinesshours(@datetime datetime) returns datetime as begin --declare @datetime datetime = '2023-09-04 19:23:39.600' declare @daystart datetime = cast(cast(@datetime as date) as datetime) declare @start_businesshour datetime = dateadd(hh,8,@daystart) declare @end_businesshour datetime = dateadd(hh,18,@daystart) if @datetime < @start_businesshour begin set @datetime = @start_businesshour end else if @datetime > @end_businesshour begin set @datetime = dateadd(day, 1, @start_businesshour) end if datepart(dw, @datetime) = 7 begin set @datetime = dateadd(day, 2, @datetime) end else if datepart(dw, @datetime) = 1 begin set @datetime = dateadd(day, 1, @datetime) end return @datetime end
select dbo.udf_tobusinesshours('2023-09-02 19:23:39.600')
--homework #1: create same function with case statement or any other approach.
- Assistant
Here is the modified function using a CASE statement:
CREATE FUNCTION udf_tobusinesshours (@datetime DATETIME) RETURNS DATETIME AS BEGIN DECLARE @daystart DATETIME = CAST(CAST(@datetime AS DATE) AS DATETIME) DECLARE @start_businesshour DATETIME = DATEADD(HOUR, 8, @daystart) DECLARE @end_businesshour DATETIME = DATEADD(HOUR, 18, @daystart)
SET @datetime = CASE WHEN @datetime < @start_businesshour THEN @start_businesshour WHEN @datetime > @end_businesshour THEN DATEADD(DAY, 1, @start_businesshour) ELSE @datetime END SET @datetime = CASE WHEN DATEPART(DW, @datetime) = 7 THEN DATEADD(DAY, 2, @datetime) WHEN DATEPART(DW, @datetime) = 1 THEN DATEADD(DAY, 1, @datetime) ELSE @datetime END RETURN @datetimeEND
SELECT dbo.udf_tobusinesshours('2023-09-02 19:23:39.600')
This function has the same functionality as the original function, but the logic is implemented using a CASE statement instead of IF statements.
- User
Write a query to display the employee number, last name, first name, and sum of invoice totals for all employees who completed an invoice. Sort the output by employee last name and then by first name (Figure P7.61).
- Assistant
Based on the information provided, I assume there are three tables involved: Employees, Invoices, and InvoiceDetails. Here's the query that will display the desired output:
SELECT e.EmployeeNumber, e.LastName, e.FirstName, SUM(i.TotalAmount) AS InvoiceTotal FROM Employees e JOIN Invoices i ON e.EmployeeID = i.EmployeeID JOIN InvoiceDetails id ON i.InvoiceID = id.InvoiceID GROUP BY e.EmployeeNumber, e.LastName, e.FirstName ORDER BY e.LastName, e.FirstName;This query joins the Employees, Invoices, and InvoiceDetails tables together using appropriate join conditions. It then groups the results by the employee's number, last name, and first name, and calculates the sum of invoice totals using the SUM() function. Finally, the results are sorted by employee last name and then by first name.