Sql在每个继续组中获得第一行

时间:2014-09-04 16:09:04

标签: sql

我遇到了一个关于获取每组顶行的SQL问题。我搜索了现有的答案,这是关于从不同的群体中获得最高的答案。在我的情况下,我有重复的组。例如,

enter image description here

这个表按“地点日期”排序,只要他们的“订单名称”或“订单量”与前一行不同,我想得到的就是每个组的顶行。所以输出应该是,

enter image description here

row_number ...按功能分区在这里不起作用。我也试过功能连接。但它似乎也不起作用。

提前感谢!

1 个答案:

答案 0 :(得分:0)

如果您使用的是SQL Server,则可以使用:

CREATE TABLE #Test
(
OrderID     INT,
OrderName   VARCHAR(400),
OrderVolume INT,
PlacedDate  DATE,
Visit_Key   INT
)

INSERT INTO #Test VALUES(1,'A',24,'10/12/2012',432)
INSERT INTO #Test VALUES(2,'A',24,'10/13/2012',432)
INSERT INTO #Test VALUES(3,'A',24,'10/14/2012',432)
INSERT INTO #Test VALUES(4,'B',27,'10/18/2012',432)
INSERT INTO #Test VALUES(5,'B',27,'10/18/2012',432)
INSERT INTO #Test VALUES(6,'A',24,'11/25/2012',432)
INSERT INTO #Test VALUES(7,'A',24,'11/25/2012',432)
INSERT INTO #Test VALUES(8,'A',24,'11/25/2012',432)

CREATE TABLE #Test2
(
OrderID             INT,
OrderName           VARCHAR(400),
OrderVolume         INT,
PlacedDate          DATE,
Visit_Key           INT,
Prev_ordervol       INT
)
INSERT INTO #Test2
(
OrderID,            
OrderName,      
OrderVolume ,   
PlacedDate,     
Visit_Key,      
Prev_ordervol
)
SELECT
    MIN(OrderID) AS 'orderid',
    ordername,
    ordervolume,
    MIN(placeddate) AS 'placeddate',
    MIN(Visit_Key) AS 'visit_key',
    LAG(OrderVolume)  OVER (ORDER BY orderid) AS 'previous ordervol' 
FROM #Test
GROUP BY OrderVolume, ordername, orderid, placeddate



SELECT
    OrderID,
    OrderName,
    OrderVolume,
    PlacedDate,
    Visit_Key
FROM #Test2
WHERE OrderVolume != Prev_ordervol OR Prev_ordervol IS NULL

DROP TABLE #Test
DROP TABLE #Test2