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

replace NULL values with latest non-NULL value in resultset series (SQL Server 2008 R2)

You can try the following: * Updated ** — Test Data DECLARE @YourTable TABLE(Product INT, Timestamp DATETIME, Price NUMERIC(16,4)) INSERT INTO @YourTable SELECT 5678, ‘20080101 12:00:00’, 12.34 UNION ALL SELECT 5678, ‘20080101 12:01:00’, NULL UNION ALL SELECT 5678, ‘20080101 12:02:00’, NULL UNION ALL SELECT 5678, ‘20080101 12:03:00’, 23.45 UNION ALL SELECT 5678, ‘20080101 12:04:00’, NULL … Read more

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

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

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