1

我这里是我的桌子

Type | Price | Date
chair| 10    | 04/05/2013
chair| 15    | 03/07/2012
chair| 11    |01/01/2011
sofa | 100   |01/08/2011
sofa | 120   |03/09/2013
sofa | 150   |07/07/2010

对于每种不同的类型,我想提取最新价格,所以我的查询结果应该是

Type  | Price | Date
chair | 10    | 04/05/2013
sofa  | 120   |03/09/2013

我一遍又一遍地尝试分组,但到目前为止没有运气

4

3 回答 3

4

您可以使用子查询来获取max(date)每种类型的:

select t1.type,
  t1.price,
  t1.date
from yt t1
inner join
(
  select max(date) date, type
  from yt
  group by type
) t2
  on t1.type = t2.type
  and t1.date = t2.date;

请参阅带有演示的 SQL Fiddle

或者,您可以max(date) over (partition ...)像这样使用:

select t1.type,
  t1.price,
  t1.date
from
(
  select max(date) over (partition by type) maxdate, type, price, date
  from yt
  group by type
) t1
where t1.date = t1.maxdate;

SQL Fiddle with Demo

于 2013-05-02T15:27:20.663 回答
3

您可以使用CTEwith ROW_NUMBER/ DENSE_RANK

WITH CTE AS
(
    SELECT  RN = ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Date DESC),
            Type, Price, Date
    FROM dbo.TableName
)
SELECT Type, Price, Date
FROM CTE
WHERE RN = 1

演示

ROW_NUMBER始终只返回一条记录,而 DENSE_RANK返回具有最新日期的所有记录(如果有多个具有相同的 MAX 日期)。

于 2013-05-02T15:27:20.943 回答
0

询问:

SQLFIDDLE示例

SELECT t1.type,
       t1.price,
       t1.date
FROM yt t1
WHERE t1.date = (SELECT max(t2.date)
                 FROM yt t2
                 WHERE t1.type = t2.type) 

如果最大值不够:

SELECT t1.type,
       t1.price,
       t1.date
FROM yt t1
WHERE t1.date = (SELECT TOP 1 t2.date
                 FROM yt t2
                 WHERE t1.type = t2.type
                 ORDER BY t2.date desc) 

结果:

|  TYPE | PRICE |                         DATE |
------------------------------------------------
|  sofa |   120 | March, 09 2013 00:00:00+0000 |
| chair |    10 | April, 05 2013 00:00:00+0000 |
于 2013-05-03T05:54:53.623 回答