SQL显示计数中的第一个和最后一个值

时间:2019-04-30 21:20:14

标签: sql sql-server tsql aggregate-functions northwind

我需要编写一个查询,以显示客户订单的最大订单数和最小订单数。

我尝试过:

(SELECT TOP 1 CustomerID, COUNT(*) AS Number_Of_Orders
FROM Orders
GROUP BY CustomerID
ORDER BY COUNT(*) ASC)

UNION ALL

(SELECT TOP 1 CustomerID, COUNT(*) AS Number_Of_Orders
FROM Orders
GROUP BY CustomerID
ORDER BY COUNT(*) DESC)

但是我无法在输出之间进行合并,出现错误Incorrect syntax near the keyword 'ORDER'

我该怎么办?

3 个答案:

答案 0 :(得分:5)

我不确定是否要两次运行聚合,因此请使用窗口函数:

SELECT CustomerID, Number_Of_Orders
FROM (SELECT CustomerID, COUNT(*) AS Number_Of_Orders,
             ROW_NUMBER() OVER (ORDER BY COUNT(*) ASC) as seqnum_asc,
             ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as seqnum_desc
      FROM Orders
      GROUP BY CustomerID
     ) c
WHERE seqnum_asc = 1 OR seqnum_desc = 1;

答案 1 :(得分:1)

您不能在要与ORDER BY合并的查询中使用UNION,但是您可以这样做:

SELECT * FROM
  (SELECT TOP 1 CustomerID, COUNT(*) AS Number_Of_Orders
  FROM Orders
  GROUP BY CustomerID
  ORDER BY COUNT(*) ASC) t
UNION ALL
SELECT * FROM
  (SELECT TOP 1 CustomerID, COUNT(*) AS Number_Of_Orders
  FROM Orders
  GROUP BY CustomerID
  ORDER BY COUNT(*) DESC) t

这可以解决问题,尽管它效率不高,因为您执行两次相同的代码并对两次进行排序。

答案 2 :(得分:1)

您可以为此使用窗口功能。如果有联系(fiddle),这将为您带来多个客户的最小/最大数量:

SELECT CustomerID
     , OrderCount
     , CASE WHEN OrderCount = MinOrderCount THEN 'Customer with min orders'
            WHEN OrderCount = MaxOrderCount THEN 'Customer with max orders' END AS Type
FROM (
    SELECT CustomerID
         , COUNT(*) AS OrderCount
         , MIN(COUNT(*)) OVER () AS MinOrderCount
         , MAX(COUNT(*)) OVER () AS MaxOrderCount
    FROM Orders
    GROUP BY CustomerID
) AS x
WHERE OrderCount = MinOrderCount OR OrderCount = MaxOrderCount