使用Group By的SQL复杂查询

时间:2013-10-20 12:02:22

标签: sql-server sql-server-2008 group-by

我有一张像

这样的表格
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

2 个答案:

答案 0 :(得分:1)

SQL2005 +:我会使用MAX聚合函数和OVER clause

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
...

答案 1 :(得分:0)

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

SELECT act.*,(SELECT MAX(a.create_date) maxtime FROM table a) FROM table act ;