Skip to content
Advertisement

How to select user ID who has saved the most products and the list of products he has saved

I am trying to query the user ID who has saved the most products and the list of products he has saved

+----------------+---------+
| 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

DB_fiddle

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement