-2

我有一张像

Product Id   Status          Date
1            Ordered         01/02/1999
1            Leased          02/04/2001
1            SubLeased       12/31/2000
1            Cancelled       10/25/2003

我需要在单个查询中显示该产品的所有记录以及最大(日期)。结果应该像

ProductId    Status          Date          Max(date)
1            Ordered         01/02/1999    10/25/2003
1            Leased          02/04/2001    10/25/2003
1            SubLeased       12/31/2000    10/25/2003
1            Cancelled       10/25/2003    10/25/2003
4

2 回答 2

1

SQL2005+:我会使用带有OVER 子句的 MAX 聚合函数:

SELECT  t.ProductId, t.Status, t.Date, 
        MAX(t.Date) OVER(PARTITION BY t.ProductId) AS MaxPerProductId
FROM    MySchema.MyTable AS t

例子:

SELECT  o.object_id, o.name, o.create_date,
        MAX(o.create_date) OVER() AS MaxCreateDate
FROM    sys.objects o
ORDER BY o.create_date DESC;

结果:

object_id   name                 create_date             MaxCreateDate
----------- -------------------- ----------------------- -----------------------
448720651   Persons              2013-10-19 22:29:37.503 2013-10-19 22:29:37.503
432720594   PK_Invoice_InvoiceID 2013-10-13 21:16:28.287 2013-10-19 22:29:37.503
416720537   Invoice              2013-10-13 21:16:26.560 2013-10-19 22:29:37.503
256719967   MyTable              2013-10-12 23:34:34.260 2013-10-19 22:29:37.503
224719853   spTest               2013-10-03 22:47:50.380 2013-10-19 22:29:37.503
...
于 2013-10-20T12:05:45.680 回答
0

如果mysql像下面的语句,你可以参考,

SELECT act.*,(SELECT MAX(a.create_date) maxtime FROM table a) FROM table act ;
于 2013-10-20T13:13:34.240 回答