Teradata头等和最后价值

时间:2015-11-18 06:53:10

标签: teradata

如何在特定列上获取group by的列的第一个值和最后一个值? 例如:我需要基于group by og case id的case_owner列的first_value和last_value。

2 个答案:

答案 0 :(得分:1)

第一个值:

select case_owner  as case_owner_first_value
from
table
qualify row_number() over (partition by case_id  order by case_id) = 1

最后一个值:

select case_owner  as case_owner_last_value
from
table
qualify row_number() over (partition by case_id order by case_id desc ) = 1

答案 1 :(得分:1)

请注意,在将FIRST_VALUE与ORDER BY子句组合时,可能需要在它们之间添加行。

示例:

CREATE VOLATILE TABLE test_fv (id INTEGER,seq SMALLINT) ON COMMIT PRESERVE ROWS;

INSERT INTO test_fv VALUES (NULL,1);
INSERT INTO test_fv VALUES (2,2);
INSERT INTO test_fv VALUES (3,3);
INSERT INTO test_fv VALUES (4,4);
INSERT INTO test_fv VALUES (5,5);

SELECT seq, FIRST_VALUE(id ignore NULLS) OVER (ORDER BY seq ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM test_fv;

这行不通:

SELECT seq, FIRST_VALUE(id ignore NULLS) OVER (ORDER BY seq ASC) FROM test_fv;