简体   繁体   中英

SQL join or subquery help on same table

I have a dilemma that can most likely be solved by someone who is smarter than me with SQL.

I have 1 table that consists of eCommerce orders. The table contain quite a bit of data but the most important is listed below:

Table Name: ORDERS
Column 1: Customer Name
Column 2: Order Date
Column 3: Line Item

What Im looking to do is figure out if a client place an order after their initial purchase ONLY if they purchased a specific item.

Im looking for the SQL results to show me the following:
Customer Name
Order Date 1 (First order)
Order Date 2 (Second order)
Line Item 1 (First purchase if it = "Widget 1")
Line Item 2 (Second purchase on second order date)

In the past, how Ive done is to loop through the first set of data in .php and query every row looking for the existence of Order Date 2 > Order Date 1. I just think that there may be an easier way to do this using a JOIN or subquery.

Thanks much!

assuming that the specic item is in the item column you could use a inner join on the same table

select a.`Customer Name` , a.`Order Date`, b.`Order Date`,  a.`Line Item`,  b.`Line Item`
from ORDERS a 
INNER JOIN ORDERS b ON a.`Customer Name` = b.`Customer Name` 
    AND a.`item` = b.`item`
    AND , a.`Order Date` > b.`Order Date`

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