分组并在第一行带回值

时间:2015-02-17 22:50:12

标签: oracle oracle11g oracle10g

我有查询

SELECT   ID,  TIME,  PRICE,   QTY
FROM myTable

返回:

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返回最小时间,平均价格和数量之和但是我也想第一次返回

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

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

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

谢谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

假设"第一价格"意味着"价格最早的时间"

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