如何获得最小值及其代表的年份

时间:2014-05-20 13:12:30

标签: sql subquery aggregate-functions

我在表格中有一个订单列表。这些都有针对他们的日期。如何编写查询以返回一年和相关年份中的最小订单。

SELECT Max(YearCounts.[CountForYear]) AS [MinForYear] 
FROM ( SELECT COUNT(PK) AS [CountForYear]   FROM Orders
WHERE DATEPART( year , TransactionDate) > '2002'
GROUP BY DATEPART( Year, TransactionDate ) ) YearCounts  

所以我在2003年寻找98008订单作为例子

感谢您的回答,我检查了它们,子查询选项执行得最快。我接受单引号评论,感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

只需使用TOP 1

即可
SELECT TOP 1 YearCounts.[CountForYear] AS [MinForYear], 
       YearCounts.[YEAR] 
FROM ( SELECT COUNT(PK) AS [CountForYear],
               DATEPART( year , TransactionDate)  as [YEAR]  FROM Orders
               WHERE DATEPART( year , TransactionDate) > '2002'
               GROUP BY DATEPART( Year, TransactionDate ) ) YearCounts 
ORDER BY YearCounts.[CountForYear]  

答案 1 :(得分:1)

您可以在没有子查询的情况下执行此操作,只需使用toporder by

  SELECT TOP 1 DATEPART(year, TransactionDate), COUNT(PK) AS CountForYear
  FROM Orders o
  WHERE DATEPART(year , TransactionDate) > 2002
  GROUP BY DATEPART(Year, TransactionDate ) 
  ORDER BY COUNT(PK) DESC ;

您也可以使用year功能(我个人觉得更容易阅读)来写这个:

  SELECT TOP 1 YEAR(TransactionDate), COUNT(PK) AS CountForYear
  FROM Orders o
  WHERE YEAR(TransactionDate) > 2002
  GROUP BY YEAR(TransactionDate) 
  ORDER BY COUNT(PK) DESC ;

您的原始查询在'2002'附近有单引号。这是不必要的。您应该表示没有单引号的数字常量。仅对字符串和日期常量使用单引号。