获得MIN约会

时间:2013-02-22 15:43:32

标签: sql tsql db2

我有一张表(A),看起来像:

ID     Date
1      2012/01/12
2      2012/01/01
3      2012/01/03
4      2012/03/12

如果我想抓住此查询的MIN日期,我会group by吗?

select
  a.ID,
  MIN(a.DATE),
  b.name,
  c.price
FROM
  tablea a inner join tableb b on a.ID = b.ID
  inner join tablec c b.ID = c.ID

3 个答案:

答案 0 :(得分:2)

你想要一个窗口功能。正确的表达方式是:

select a.id,
       min(a.date) over () as mindate,
       b.name, c.price
. . .

这表示获取数据的最小日期。没有分区,因此它可以覆盖所有数据。

答案 1 :(得分:1)

如果您正在寻找那些具有最短日期的人,那么您可以这样做:

select
  a.ID,
  a.DATE,
  b.name,
  c.price
FROM tablea a 
INNER JOIN
(
   SELECT Id, MIN(Date) AS MinDate 
   FROM tablea
   GROUP BY Id
) As minA ON a.date = mina.mindate AND a.id = mina.id
inner join tableb b on a.ID = b.ID
inner join tablec c b.ID = c.ID

答案 2 :(得分:0)

WITH recordList
as
(
    select  a.ID,
            a.DATE,
            b.name,
            c.price,
            DENSE_RANK() OVER (PARTITION BY a.ID
                                ORDER BY a.Date ASC) rn
    FROM    tablea a 
            inner join tableb b on a.ID = b.ID
            inner join tablec c b.ID = c.ID
)
SELECT  ID, DATE, name, Price
FROM    recordList
WHERE   rn = 1