简体   繁体   中英

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:

  • There are other rows with the same value in column A
  • Those other rows have a specific value in column B
  • Those other rows have a larger value in column C

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/2015
The 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 \nFred |  Pen |  5/20/2015 \nJane |  Bat |  5/22/2015 \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); , 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.

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.)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM