选择列的事件顺序没有组。
我目前有两张桌子,用户和优惠券
ID | first_name |
---|---|
1 | roberta |
2 | oliver |
3 | shayna |
4 | fechin |
ID | 折扣 | 用户_id |
---|---|---|
1 | 20% | 1 |
2 | 40% | 2 |
3 | 15% | 3 |
4 | 30% | 1 |
5 | 10% | 1 |
6 | 70% | 4 |
我想要什么做是从优惠券表中选择,直到我选择X用户。
因此,如果我选择x = 2,则结果表将是
ID | 折扣 | User_id |
---|---|---|
1 | 20% | 1 |
2 | 40% | 2 |
4 | 30% | 1 |
5 | 10% | 1 |
我尝试使用dense_rank
和row_number
,但他们返回每个用户_ID的出现计数,而不是订单。
SELECT id,
discount,
user_id,
dense_rank() OVER (PARTITION BY user_id)
FROM coupons
我猜我需要在多个子征服(很好)中进行此操作,其中第一个子查询将返回诸如
ID | 折扣 | user_id | order_of_of_occurence |
---|---|---|---|
1 | 20% | 1 | 2 |
40 | % | 2 | 2 |
3 | 15%3 15% | 3 | 3 |
4 | 30% | 1 | 1 1 |
5 | 10% | 1 | 1 |
6 | 70% | 4 | 4 |
,然后我可以用它来过滤我的需求。
PS:我正在使用PostgreSQL。
I currently have two tables, users and coupons
id | first_name |
---|---|
1 | Roberta |
2 | Oliver |
3 | Shayna |
4 | Fechin |
id | discount | user_id |
---|---|---|
1 | 20% | 1 |
2 | 40% | 2 |
3 | 15% | 3 |
4 | 30% | 1 |
5 | 10% | 1 |
6 | 70% | 4 |
What I want to do is select from the coupons table until I've selected X users.
so If I chose X = 2 the resulting table would be
id | discount | user_id |
---|---|---|
1 | 20% | 1 |
2 | 40% | 2 |
4 | 30% | 1 |
5 | 10% | 1 |
I've tried using both dense_rank
and row_number
but they return the count of occurrences of each user_id not it's order.
SELECT id,
discount,
user_id,
dense_rank() OVER (PARTITION BY user_id)
FROM coupons
I'm guessing I need to do it in multiple subqueries (which is fine) where the first subquery would return something like
id | discount | user_id | order_of_occurence |
---|---|---|---|
1 | 20% | 1 | 1 |
2 | 40% | 2 | 2 |
3 | 15% | 3 | 3 |
4 | 30% | 1 | 1 |
5 | 10% | 1 | 1 |
6 | 70% | 4 | 4 |
which I can then use to filter by what I need.
PS: I'm using postgresql.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经说过要参数化查询,以便可以检索X用户。我正在阅读它,因为第一个X Difinse
user_id
s 的所有优惠券id
column>列顺序。看来您的尝试很近。
dense_rank()
是正确的想法。由于您想查看整个表,因此无法使用使用分区。还需要一个分类列来确定排名。
You've stated that you want to parameterize the query so that you can retrieve X users. I'm reading that as all coupons for the first X distinct
user_id
s in couponid
column order.It appears your attempt was close.
dense_rank()
is the right idea. Since you want to look over the entire table you can't usepartition by
. And a sorting column is also required to determine the ranking.