[英]How do I select records by comparing values in columns B, C among records with same value in column A?
I want to select rows from my Postgres database that meet the following criteria: 我想从Postgres数据库中选择符合以下条件的行:
So if I had a table like this: 所以,如果我有一个这样的表:
User | Item | Date -----+------+------ Fred | Ball | 5/1/2015 Jane | Pen | 5/7/2015 Fred | Cup | 5/11/2015 Mike | Ball | 5/13/2015 Jane | Ball | 5/18/2015 Fred | Pen | 5/20/2015 Jane | Bat | 5/22/2015The search might be "what did people buy after they bought a ball?" 搜索可能是“人们在买球后买了什么?” The output I would want would be: 我想要的输出是:
\nUser | 用户| Item | 项目| Date 日期\n-----+------+------ ----- + ------ + ------\nFred | 弗雷德| Cup | 杯| 5/11/2015 2015年5月11日\nFred | 弗雷德| Pen | 笔| 5/20/2015 2015年5月20日\nJane | 简| Bat | 蝙蝠| 5/22/2015 2015年5月22日\n
I've gotten as far as SELECT * FROM orders AS or WHERE or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
我已经得到SELECT * FROM orders AS or WHERE or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
, which gives me all of Fred's and Jane's orders (since they ordered multiple things). ,这给了我所有弗雷德和简的命令(因为他们订购了多件事)。 But when I try to put additional limitations on the WHERE clause (eg SELECT * FROM orders AS or WHERE or.item = 'Ball' AND or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
, I get something that isn't what I expect at all -- a list of records where item = 'Ball' that seems to have ignored the second part of the query. 但是当我试图对WHERE子句施加额外限制时(例如SELECT * FROM orders AS or WHERE or.item = 'Ball' AND or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);
我得到的东西根本不是我期望的 - 一个记录列表,其中item ='Ball'似乎忽略了查询的第二部分。
Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。
Edit: Sorry, I misled some people at the end by describing the bad approach I was taking. 编辑:对不起,我最后通过描述我正在采取的糟糕方法误导了一些人。 (I was working on getting a list of the Ball purchases, which I could use as a subquery in a next step, but people correctly noted that this is an unnecessarily complex/expensive approach.) (我正在努力获取Ball购买列表,我可以在下一步中将其用作子查询,但人们正确地指出这是一种不必要的复杂/昂贵的方法。)
I think this might give the result you are looking for: 我想这可能会给你想要的结果:
SELECT orders.user, orders.item, orders.date
FROM orders, (SELECT * FROM orders WHERE item = 'ball') ball_table
WHERE orders.user = ball_table.user AND orders.date > ball_table.date;
select b.*
from user_table a
join user_table b
on b.user = a.user
and b.date > a.date
and b.item = 'Ball'
SELECT DISTINCT t3.*
FROM mytable t1
INNER JOIN mytable t2
ON t1.Item = t2.Item AND t1.User <> t2.User
INNER JOIN mytable t3
ON t2.User = t3.User AND t2.Date <= t3.Date
WHERE t1.Item = "Ball"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.