我知道我可以使用以下语法从子查询中选择一列:
SELECT A.SalesOrderID, A.OrderDate, ( SELECT TOP 1 B.Foo FROM B WHERE A.SalesOrderID = B.SalesOrderID ) AS FooFromB FROM A WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
但是使用子查询中的多个列的正确语法是什么(在我的例子中是select top 1子查询)?非常感谢你.
这里通常是如何从子查询中选择多个列:
SELECT A.SalesOrderID, A.OrderDate, SQ.Max_Foo, SQ.Max_Foo2 FROM A LEFT OUTER JOIN ( SELECT B.SalesOrderID, MAX(B.Foo) AS Max_Foo, MAX(B.Foo2) AS Max_Foo2 FROM B GROUP BY B.SalesOrderID ) AS SQ ON SQ.SalesOrderID = A.SalesOrderID
如果你最终想要做的是从Foo的最高值的行中获取值(而不是Foo的最大值和Foo2的最大值 - 这不是同一个东西),那么以下通常会比子查询:
SELECT A.SalesOrderID, A.OrderDate, B1.Foo, B1.Foo2 FROM A LEFT OUTER JOIN B AS B1 ON B1.SalesOrderID = A.SalesOrderID LEFT OUTER JOIN B AS B2 ON B2.SalesOrderID = A.SalesOrderID AND B2.Foo > B1.Foo WHERE B2.SalesOrderID IS NULL
你基本上是在说,给我B行,我找不到B中的任何其他行,具有相同的SalesOrderID和更大的Foo.
SELECT a.salesorderid, a.orderdate, s.orderdate, s.salesorderid FROM A a OUTER APPLY (SELECT top(1) * FROM B b WHERE a.salesorderid = b.salesorderid) as s WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
你必须加入:
SELECT A.SalesOrderID, B.Foo FROM A JOIN B bo ON bo.id = ( SELECT TOP 1 id FROM B bi WHERE bi.SalesOrderID = a.SalesOrderID ORDER BY bi.whatever ) WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
,假设b.id
是PRIMARY KEY
开启的B
在MS SQL 2005
和更高的你可以使用这个语法:
SELECT SalesOrderID, Foo FROM ( SELECT A.SalesOrderId, B.Foo, ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn FROM A JOIN B ON B.SalesOrderID = A.SalesOrderID WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4' ) i WHERE rn
这将从B
每个记录中精确选择一条记录SalesOrderId
.