注册 登录
编程论坛 SQL Server论坛

有大佬能帮我看看这个怎么写吗

fuckamerica 发布于 2022-10-14 14:55, 977 次点击
Please write a query to get the top 3 item_id (has most distinct order_ids) for each category and their order count together with its rank for each category.
Table: item_sales_information
 
+-------------+----------+
| Column Name | Type |
+-------------+----------+
| item_id | int |
| order_id | int |
| category | varchar |
| sold_date | timestamp|
+-------------+----------+
 
Your query should return the following output for the above table:
 
+----------+---------------+------------+------+
| item_id | order_count | category | rank |
+----------+---------------+------------+------+
| t3902 | 2599 | Clothes | 1 |
| t7892 | 2320 | Clothes | 2 |
| t1829 | 1878 | Clothes | 3 |
| k1290 | 1299 | Shoes | 1 |
| k4729 | 872 | Shoes | 2 |
| k0173 | 729 | Shoes | 3 |
... |
+----------+---------------+------------+------+
1 回复
#2
秋末茗塘2022-12-15 16:20
SELECT item_id
      ,order_id AS order_count
      ,category
      ,ROW_NUMBER() OVER(PARTITION BY category ORDER BY order_id DESC) rank
FROM table_1
1