Using GROUP BY with FIRST_VALUE and LAST_VALUE

SELECT MIN(MinuteBar) AS MinuteBar5, Opening, MAX(High) AS High, MIN(Low) AS Low, Closing, Interval FROM ( SELECT FIRST_VALUE([Open]) OVER (PARTITION BY DATEDIFF(MINUTE, ‘2015-01-01 00:00:00’, MinuteBar) / 5 ORDER BY MinuteBar) AS Opening, FIRST_VALUE([Close]) OVER (PARTITION BY DATEDIFF(MINUTE, ‘2015-01-01 00:00:00’, MinuteBar) / 5 ORDER BY MinuteBar DESC) AS Closing, DATEDIFF(MINUTE, ‘2015-01-01 00:00:00’, MinuteBar) / 5 AS Interval, … Read more

Oracle ‘Partition By’ and ‘Row_Number’ keyword

PARTITION BY segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently. In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER But … Read more

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It’s the “frame” or “range” clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata. A simple example would be to calculate the average amount in a frame of three days. I’m using PostgreSQL syntax for the example, but it will be the same for Teradata: WITH … Read more

MySQL get row position in ORDER BY

Use this: SELECT x.id, x.position, x.name FROM (SELECT t.id, t.name, @rownum := @rownum + 1 AS position FROM TABLE t JOIN (SELECT @rownum := 0) r ORDER BY t.name) x WHERE x.name=”Beta” …to get a unique position value. This: SELECT t.id, (SELECT COUNT(*) FROM TABLE x WHERE x.name <= t.name) AS position, t.name FROM TABLE … Read more

Calculating Cumulative Sum in PostgreSQL

Basically, you need a window function. That’s a standard feature nowadays. In addition to genuine window functions, you can use any aggregate function as window function in Postgres by appending an OVER clause. The special difficulty here is to get partitions and sort order right: SELECT ea_month, id, amount, ea_year, circle_id , sum(amount) OVER (PARTITION … Read more