Advertisement
elena1234

Function with Common Table Expression ( T-SQL )

Jan 11th, 2022 (edited)
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.80 KB | None | 0 0
  1. --Create a function ufn_CashInUsersGames that sums the cash of odd rows. Rows must be ordered by cash in descending order. The function --should take a game name as a parameter and return the result as table. Submit only your function in.
  2. --Execute the function over the following game names, ordered exactly like: "Love in a mist".
  3.  
  4.  
  5. CREATE OR ALTER FUNCTION ufn_CashInUsersGames (@GameName nvarchar(100))
  6. RETURNS TABLE
  7. AS
  8. RETURN
  9. (
  10.    WITH CTE (Name, GameId, CASH, Row#)
  11.    AS
  12.    (
  13.        SELECT Games.Name, UsersGames.GameId, UsersGames.CASH,
  14.        ROW_NUMBER() OVER(ORDER BY UsersGames.CASH DESC) AS Row#
  15.        FROM UsersGames
  16.        JOIN Games ON Games.ID = UsersGames.GameId
  17.        WHERE Games.Name = @GameName
  18.     )  
  19.  
  20.     SELECT SUM(CTE.CASH) AS SumCash
  21.     FROM CTE
  22.     WHERE Row# % 2 = 1
  23. )
  24. GO
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement