Fibonacci (SQL Server 2012)

this is another fibonacci logic besides my previous method with simpler query syntax using SQL Server 2012 or higher version. please contact me if you know better query syntax, i really appreciate that.

below my code:

IF OBJECT_ID('TMP_CUSTOMER') IS NOT NULL
 DROP TABLE TMP_CUSTOMER
 
CREATE TABLE TMP_CUSTOMER
(
 CUSTOMER_ID INT IDENTITY PRIMARY KEY,
 CUSTOMER_CODE VARCHAR(10),
 CUSTOMER_VALUE INT
)
 
INSERT INTO TMP_CUSTOMER
SELECT 'CODE1', 1 UNION ALL
SELECT 'CODE1', 2 UNION ALL
SELECT 'CODE1', 3 UNION ALL
SELECT 'CODE2', 4 UNION ALL
SELECT 'CODE2', 5 UNION ALL
SELECT 'CODE2', 6 UNION ALL
SELECT 'CODE3', 7 UNION ALL
SELECT 'CODE3', 8 UNION ALL
SELECT 'CODE4', 9 UNION ALL
SELECT 'CODE4', 10 
 
/* FIBONACCI GENERAL */
SELECT 
 *,
 SUM(CUSTOMER_VALUE) OVER (ORDER BY CUSTOMER_ID)
FROM TMP_CUSTOMER
 
/* FIBONACCI BY CUSTOMER CODE */
SELECT 
 *,
 SUM(CUSTOMER_VALUE) OVER (PARTITION BY CUSTOMER_CODE ORDER BY CUSTOMER_ID)
FROM TMP_CUSTOMER

CMIIW 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Afiseaza emoticoanele Locco.Ro