查询列出公司名称和第一个订单日期

时间:2013-12-09 22:29:48

标签: sql sql-server-2012 filtering

正如标题所说,我正在尝试编写一个查询,显示客户ID,公司名称和第一个订单的日期(列出的最早日期)。我试过Top 1但是没有用。使用SQL Server 2012。

Select c.CustomerID, CompanyName, top 1 o.OrderDate as 'first order date'
from Customers c join Orders o on
c.CustomerID = o.CustomerID 
order by c.CustomerID 

任何建议或帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

select c.CustomerID, CompanyName, MIN(o.OrderDate) as 'first order date'
from
    Customers c
    join Orders o on c.CustomerID = o.CustomerID
group by c.CustomerID, CompanyName 
order by c.CustomerID 

答案 1 :(得分:1)

此解决方案更灵活,因为它允许您添加Customers表中的任何列,而无需将它们添加到GROUP BY

;WITH x AS 
(
  SELECT CustomerID, OrderDate = MIN(OrderDate)
  FROM dbo.Orders GROUP BY CustomerID
)
SELECT c.CustomerID, c.CompanyName, x.OrderDate
  FROM dbo.Customers AS c
  INNER JOIN x ON c.CustomerID = x.CustomerID
  ORDER BY c.CustomerID;

如果你想要第一个订单中的其他列,例如订单总数,你可以这样做,使用GROUP BY时无法添加,因为最便宜或最昂贵的订单,例如,不一定与第一个订单相对应:

;WITH x AS 
(
  SELECT CustomerID, OrderDate, TotalAmount, /* ...other columns... */
    rn = ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate)
  FROM dbo.Orders GROUP BY CustomerID
)
SELECT c.CustomerID, c.CompanyName, x.OrderDate, x.TotalAmount /* ...others... */
  FROM dbo.Customers AS c
  INNER JOIN x ON c.CustomerID = x.CustomerID
  WHERE x.rn = 1
  ORDER BY c.CustomerID;