分组并返回第一行的值

Group by and bring back value in first row

我有疑问

SELECT   ID,  TIME,  PRICE,   QTY
FROM myTable

returns:

ID             TIME             PRICE   QTY
1295179228  1/29/2015 20:59:37  15.24   1112
1295179228  1/29/2015 20:59:37  15.23   2
1295179228  1/29/2015 20:59:38  15.28   22
1295179228  1/29/2015 20:59:38  15.27   1800

然后我使用 group by 来 return 最短时间、平均价格和数量总和,但我也想 return 第一次

SELECT   ID, t2.name, min(TIME) as MinTIME, avg(PRICE) as AVGPrice, sum( QTY) as SUMQTY
FROM myTable t inner join table2 t2 on t.id = t2.id
group by ID, t2.name

但是我如何通过上面的查询在该组中添加一列,这也将 return 第一个 PRICE。在那种情况下就是 15.24

我一直在谷歌搜索,我看到 oracle 有 FIRST() 和 FIRST_VALUE() 函数,但我无法让它们工作。

谢谢。

WITH CTE AS
(SELECT ID,"TIME",PRICE,QTY,ROW_NUMBER() OVER (PARTITION BY id ORDER BY TIME ASC) as rn
FROM t)
SELECT ID, min("TIME") as MinTIME, avg(PRICE) as AVGPrice, sum( QTY) as SUMQTY,
MAX(CASE WHEN rn=1 THEN PRICE ELSE 0 END) as FirstPrice
FROM CTE
group by ID

假设"first price"表示"price with the earliest time"

min(price) keep (dense_rank first order by time)