简体   繁体   English

在同一表上的SQL连接或子查询帮助

[英]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. 我有一个难题,最有可能是比SQL更聪明的人解决了。

I have 1 table that consists of eCommerce orders. 我有1个表,其中包含电子商务订单。 The table contain quite a bit of data but the most important is listed below: 该表包含很多数据,但是最重要的数据在下面列出:

Table Name: ORDERS 表格名称:ORDERS
Column 1: Customer Name 第1栏:客户名称
Column 2: Order Date 第2栏:订购日期
Column 3: Line Item 第3列:订单项

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: 我正在寻找SQL结果以显示以下内容:
Customer Name 顾客姓名
Order Date 1 (First order) 订单日期1 (第一订单)
Order Date 2 (Second order) 订单日期2 (第二订单)
Line Item 1 (First purchase if it = "Widget 1") 订单项1 (如果它=“窗口小部件1”,则首次购买)
Line Item 2 (Second purchase on second order date) 订单项2 (第二购买日期为第二次购买)

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. 过去,我的工作是遍历.php中的第一组数据并查询每一行,以查找是否存在Order Date 2> Order Date1。我只是认为可以使用以下方法更简单地执行此操作JOIN或子查询。

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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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