elena1234

FOR XML PATH With STUFF ( T-SQL )

Mar 8th, 2022 (edited)
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.40 KB | None | 0 0
  1. USE [AdventureWorks2019]
  2. GO
  3.  
  4.  
  5. -- Exercise 1
  6. -- Create a query that displays all rows from the Production.ProductSubcategory table, and includes the following fields:
  7. -- The "Name" field from Production.ProductSubcategory, which should be aliased as "SubcategoryName"
  8. -- A derived field called "Products" which displays, for each Subcategory in Production.ProductSubcategory,
  9. -- a semicolon-separated list of all products from Production.Product contained within the given subcategory
  10. -- Hint: Production.ProductSubcategory and Production.Product are related by the "ProductSubcategoryID" field.
  11. SELECT SubcategoryName = A.NAME,
  12. Products =
  13. STUFF(
  14. (
  15. SELECT ', ' + B.Name
  16. FROM Production.Product AS B
  17. WHERE A.ProductSubcategoryID = B.ProductSubcategoryID
  18. FOR XML PATH('')
  19. ),
  20. 1, 1, '')
  21. FROM Production.ProductSubcategory AS A
  22.  
  23.  
  24. -- Exercise 2
  25. -- Modify the query from Exercise 1 such that only products with a ListPrice value greater than $50 are included in the "Products" field.
  26. -- Hint: Assuming you used a correlated subquery in Exercise 1, keep in mind that you can apply additional criteria to it,
  27. -- just as with any other correlated subquery.
  28. SELECT SubcategoryName = A.NAME,
  29. Products =
  30. STUFF(
  31. (
  32. SELECT ', ' + B.Name
  33. FROM Production.Product AS B
  34. WHERE A.ProductSubcategoryID = B.ProductSubcategoryID
  35. AND B.ListPrice > 50
  36. FOR XML PATH('')
  37. ),
  38. 1, 1, '')
  39. FROM Production.ProductSubcategory AS A
  40.  
Add Comment
Please, Sign In to add comment