简体   繁体   English

在同一张桌子上“加入” 2个不同的选择?

[英]“Joining” 2 different selects on the same table?

I have a table of orders with products, each product has their own shipping date. 我有一张带有产品的订单表,每种产品都有自己的发货日期。 How can I retrieve the orders so it shows the fastest shipping date? 如何获取订单,以显示最快的发货日期?

For example: 例如:

Order  Product  Ship date
1      phone    02/03/2019
1      charger  02/07/2019
2      printer  03/01/2019

What would be the sql query to retrieve the following? sql查询检索以下内容是什么?

Order  Product  Ship date
1      phone    02/03/2019
1      charger  02/03/2019
2      printer  03/01/2019

Ie on order 1, all ship dates are 02/03/2019 since it's the earliest. 即在订单1上,所有船舶的最早日期都是02/03/2019。

I tried this: 我尝试了这个:

SELECT order, 
       product,
       (SELECT ship_date FROM Tracking ORDER BY ship_date ASC) tbl ON tbl.order = t.order
FROM Tracking t

But I'm getting the error: 但是我得到了错误:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

To get rid of the "The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified." 要摆脱“除非指定TOP或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公共表表达式中无效”。 message, you can do that by adding "SELECT TOP 100 PERCENT" to the sub-query. 消息,您可以通过在子查询中添加“ SELECT TOP 100 PERCENT”来实现。 But I'd suggest looking into the RANK and DENSE_RANK functions as they're probably going to be more helpful 但是我建议研究一下RANK和DENSE_RANK函数,因为它们可能会更有用

Considering the error message I believe this is for SQL Server and thus window functions to be available. 考虑到错误消息,我认为这是针对SQL Server的,因此可以使用窗口功能。

You could use the windowed version of min() to get the minimum shipping date for an order. 您可以使用min()的窗口版本来获取订单的最小发货日期。

SELECT [order],
       [product],
       min([ship date]) OVER (PARTITION BY [order]) [ship date]
       FROM tracking;           

I am not sure that i understand what you are trying to achieve here. 我不确定我是否理解您在这里想要实现的目标。 Well if you want just to query this table ordered by shipping date, i think something like this would work: 好吧,如果您只想查询按发货日期排序的表,我认为这样会起作用:

SELECT * FROM Tracking ORDER BY ship_date ASC; 

You are making it very complicated. 您正在使其变得非常复杂。 The query is pretty simple: 查询非常简单:

select * from my_table group by shipdate order by shipdate asc

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

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