嵌套查询与最新记录

时间:2013-02-15 16:45:43

标签: sql sql-server sql-server-2008

我正在研究SQL Server 2008数据库。我需要获取客户的特定订单及其最新订单ID和最新订单数据。我的挑战是,我需要一行数据。目前,我正在尝试以下查询:

 SELECT
  o.*,
  c.[FirstName],
  c.[LastName],
  c.[PlayerName],
  (SELECT TOP 1 o2.CreatedDate, o2.ID  FROM [Order] o2 ORDER BY [CreatedOn] DESC)
 FROM
  [Order] o,
  [Customer] c
 WHERE  
  o.[ID]=c.[CustomerID]

执行此查询时,出现以下错误:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

您可以想象,有些情况下客户不会有先前的订单。我该怎么做并将结果放到一行?

谢谢!

2 个答案:

答案 0 :(得分:2)

 SELECT
  o.*,
  c.[FirstName],
  c.[LastName],
  c.[PlayerName],
  (SELECT TOP 1 o2.CreatedDate FROM [Order] o2 ORDER BY [CreatedOn] DESC),
  (SELECT TOP 1 o2.ID FROM [Order] o2 ORDER BY [CreatedOn] DESC)
 FROM
  [Order] o,
  [Customer] c
 WHERE  
  o.[ID]=c.[CustomerID]

错误是说您无法在子查询中选择两个字段。所以你必须单独完成它们。

答案 1 :(得分:2)

使用CTE的方式略有不同。

WITH LatestOrder AS (SELECT TOP 1 * FROM [Order] ORDER BY [CreatedOn] DESC) 
 SELECT
  o.*,
  c.[FirstName],
  c.[LastName],
  c.[PlayerName],
  lo.CreatedDate,
  lo.ID
 FROM [Order] o
 JOIN [Customer] c
    ON o.[ID]=c.[CustomerID]
 CROSS JOIN LatestOrder lo