如何在 T-SQL 中按一列分组并按另一列排序

How to GROUP BY one column and ORDER BY another in T-SQL

我有 table 件具有某些价值的物品,其中包括成本和购买日期。我正在尝试获取最昂贵商品的列表,每种商品类型一个,按该特定商品的购买日期排序,结果中没有购买日期。

我的table(简体):

CREATE TABLE Purchases
    (ItemType varchar(25),
    Cost int,
    PurchaseDate smalldatetime)

我的示例数据:

INSERT INTO Purchases VALUES
    ('Hat',     0,      '2007-05-20 15:22'),
    ('Hat',     0,      '2007-07-01 15:00'),
    ('Shirt',   3500,   '2007-07-30 08:43'),
    ('Pants',   2000,   '2008-07-30 12:00'),
    ('Pants',   4000,   '2009-03-15 07:30'),
    ('Sweater', 3000,   '2011-05-20 15:22'),
    ('Sweater', 3750,   '2012-07-01 22:00'),
    ('Sweater', 2700,   '2014-06-12 11:00'),
    ('Hat',     4700,   '2015-06-29 07:10')

我的预期输出(为清楚起见添加日期):

ItemType                MostExpensivePerType
------------------------- --------------------
Shirt                     3500                (2007-07-30 08:43)
Pants                     4000                (2009-03-15 07:30)
Sweater                   3750                (2012-07-01 22:00)
Hat                       4700                (2015-06-29 07:10)

我目前的工作:

我反复尝试过,我最好的结果是这个查询:

SELECT 
    ItemType, MAX(Cost) AS MostExpensivePerType 
FROM 
    Purchases 
GROUP BY 
    ItemType 
ORDER BY 
    MostExpensivePerType DESC

每个项目类型产生最昂贵的项目,但按成本排序。如果没有 ORDER BY 子句,它们似乎是按字母顺序排列的。我意识到我的查询中也需要日期列,但我可以输入它并在结果中 'hide' 它吗?还是我需要将到目前为止的结果保存在临时 table 中并加入我的常规 table?最好的方法是什么?

SQL Fiddle here!

使用window函数:

select ItemType, Cost MostExpensivePerType
from (select p.*,
             row_number() over (partition by itemtype order by cost desc) as seqnum
      from purchases p
     ) t
where seqnum = 1
order by PurchaseDate;

SQLFiddle here.

SELECT 
  ItemType, 
  MAX(Cost) AS MostExpensivePerType
FROM 
  Purchases 
GROUP BY 
  ItemType 
ORDER BY
  Max(PurchaseDate) DESC
SELECT a.ItemType,a.MostExpensivePerType 
FROM (
  SELECT ItemType, MAX(Cost) AS MostExpensivePerType , MAX(PurchaseDate) AS MaxPurchaseDate 
  FROM Purchases 
  GROUP BY ItemType
  ) a
  ORDER BY a.MaxPurchaseDate DESC