Ho un database che memorizza le informazioni sui costi per un'organizzazione, suddivisi per divisione e tempistiche per anno. La struttura dei costi coinvolge una relazione genitore-figlio; gli utenti possono specificare i valori di costo su qualsiasi livello nella struttura, l'unica restrizione è che tutti i valori ai livelli superiori nella gerarchia sono calcolati come la somma dei nodi figli, se qualsiasi nodo figlio ha un valore; i valori del nodo genitore che risultano come somma dei nodi figli non sono memorizzati nel database.Somma ricorsiva nella gerarchia padre-figlio T-SQL
ho bisogno di una query che ricorsivamente calcolare i valori dei genitori in base alle loro figli e per i bambini senza valori zero sarà impostato (T-SQL, SQL 2008R2)
[SQL Fiddle] MS SQL Server 2008 Schema di installazione:
CREATE TABLE CostStructureNodes (
Id INT NOT NULL PRIMARY KEY,
Name NVARCHAR(250) NOT NULL,
ParentNodeId INT,
FOREIGN KEY(ParentNodeId) REFERENCES CostStructureNodes(Id)
);
CREATE TABLE Years (
Year INT NOT NULL PRIMARY KEY
);
CREATE TABLE CostsPerYear (
NodeId INT NOT NULL,
Year INT NOT NULL,
Value DECIMAL(18,6) NOT NULL,
PRIMARY KEY(NodeId, Year),
FOREIGN KEY(NodeId) REFERENCES CostStructureNodes(Id),
FOREIGN KEY(Year) REFERENCES Years(Year)
);
INSERT INTO CostStructureNodes VALUES ('1', 'Total Costs', NULL);
INSERT INTO CostStructureNodes VALUES ('2', 'R&D', 1);
INSERT INTO CostStructureNodes VALUES ('3', 'Legal', 1);
INSERT INTO CostStructureNodes VALUES ('4', 'HR', 1);
INSERT INTO CostStructureNodes VALUES ('5', 'IT', 1);
INSERT INTO CostStructureNodes VALUES ('6', 'Software', 5);
INSERT INTO CostStructureNodes VALUES ('7', 'Hardware', 5);
INSERT INTO Years VALUES (2010);
INSERT INTO Years VALUES (2011);
INSERT INTO Years VALUES (2012);
INSERT INTO CostsPerYear VALUES (1, 2010, 100000);
INSERT INTO CostsPerYear VALUES (2, 2011, 50000);
INSERT INTO CostsPerYear VALUES (5, 2011, 20000);
INSERT INTO CostsPerYear VALUES (6, 2012, 22000);
INSERT INTO CostsPerYear VALUES (7, 2012, 13000);
INSERT INTO CostsPerYear VALUES (2, 2012, 76000);
Data la struttura di cui sopra ed i dati di esempio, questo è come le cose sarebbero simile:
| NAME | YEAR | VALUE |
-------------------------------
| Total Costs | 2010 | 100000 |
| R&D | 2010 | 0 |
| IT | 2010 | 0 |
| Software | 2010 | 0 |
| Hardware | 2010 | 0 |
| HR | 2010 | 0 |
| Total Costs | 2011 | 70000 |
| R&D | 2011 | 50000 |
| IT | 2011 | 20000 |
| Software | 2011 | 0 |
| Hardware | 2011 | 0 |
| HR | 2011 | 0 |
| Total Costs | 2012 | 111000 |
| R&D | 2012 | 76000 |
| IT | 2012 | 35000 |
| Software | 2012 | 22000 |
| Hardware | 2012 | 13000 |
| HR | 2012 | 0 |
Potresti ricontrollare l'output richiesto. Dato che HR ha ID 4 e inserisci 75000 per HR nel 2012, nell'ultima riga dello schema di esempio. Ho difficoltà a capire che HR ha un valore di 0 per il 2012 nell'output richiesto. – souplex
Ho corretto i dati di esempio inseriti. – kjv