I am trying to query the user ID who has saved the most products and the list of products he has saved
x
+----------------+---------+
| Saved products | user_id |
+----------------+---------+
| A | 105531 |
| B | 295014 |
| C | 104230 |
| D | 55023 |
| E | 234510 |
| E | 105531 |
| …… | …… |
| F | 234510 |
| K | 2512201 |
| M | 2253121 |
| O | 3000451 |
+----------------+---------+
Advertisement
Answer
The following query should do what you want:
SELECT TOP 1 WITH TIES [User_ID]
,STRING_AGG([Product],',') AS [Product List]
,COUNT(DISTINCT([Product])) AS [Products Count]
FROM YourTable
GROUP BY [User_ID]
ORDER BY [Products Count] DESC