|
| 1 | +select c.Name, c.Contact, STRING_AGG(p.Name,',') as Products |
| 2 | +from Company c |
| 3 | + join Product p on c.CompanyID = p.CompanyID |
| 4 | +group by c.CompanyID, c.Name, c.Contact |
| 5 | + |
| 6 | +select c.Name, c.Contact, |
| 7 | + '[' + STRING_AGG('"' + STRING_ESCAPE(p.Name) + '"',',') + ']' as Products |
| 8 | +from Company c |
| 9 | + join Product p on c.CompanyID = p.CompanyID |
| 10 | +group by c.CompanyID, c.Name, c.Contact |
| 11 | + |
| 12 | +select c.Name, c.Contact, |
| 13 | + JSON_QUERY('[' + STRING_AGG('"' + STRING_ESCAPE(p.Name) + '"',',') + ']') as Products |
| 14 | +from Company c |
| 15 | + join Product p on c.CompanyID = p.CompanyID |
| 16 | +group by c.CompanyID, c.Name, c.Contact |
| 17 | +for json path; |
| 18 | + |
| 19 | +WITH CustomerAlsoBuy as ( |
| 20 | +select p.ProductID, p2.Name, p2.ProductID as RelatedProductID, |
| 21 | + ROW_NUMBER() OVER (PARTITION BY p.ProductID ORDER BY count(ol2.OrderID) desc) orders |
| 22 | +from Product p |
| 23 | + join OrderLines ol1 |
| 24 | + on p.ProductID = ol1.ProductID |
| 25 | + join OrderLines ol2 |
| 26 | + on ol1.OrderID = ol2.OrderID |
| 27 | + and ol1.ProductID <> ol2.ProductID |
| 28 | + join Product p2 |
| 29 | + on ol2.ProductID = p2.ProductID |
| 30 | +group by p.ProductID, p.Name, p2.ProductID, p2.Name |
| 31 | +) |
| 32 | +select ProductID, |
| 33 | + '['+STRING_AGG( |
| 34 | + CONCAT('{"ProductID":',RelatedProductID,',"Product":"',STRING_ESCAPE(Name,'json'),'"}'),',') + ']' Products |
| 35 | +from CustomerAlsoBuy |
| 36 | +where orders <= 5 |
| 37 | +group by ProductID |
0 commit comments