>Questo e' l'esempio che mi hai chiesto:
<SNIP>
Questa è una soluzione basata su una Common Table Expression ricorsiva (per SQL Server 2005):
USE tempdb;
CREATE TABLE dbo.distinte (
padre VARCHAR(15) NOT NULL,
figlio VARCHAR(15) NOT NULL,
quantita DECIMAL(14,6) NOT NULL);
INSERT INTO dbo.distinte VALUES ('A1', 'B1', 1); --Ha figli
INSERT INTO dbo.distinte VALUES ('A1', 'B2', 2); --Ha figli
INSERT INTO dbo.distinte VALUES ('A1', 'B3', 1.5);
INSERT INTO dbo.distinte VALUES ('B1', 'C1', 2.5);
INSERT INTO dbo.distinte VALUES ('B1', 'C2', 5); --Ha figli
INSERT INTO dbo.distinte VALUES ('B1', 'C3', 0.78);
INSERT INTO dbo.distinte VALUES ('B1', 'C4', 1.25);
INSERT INTO dbo.distinte VALUES ('B2', 'C5', 2);
INSERT INTO dbo.distinte VALUES ('B2', 'C2', 1); --Ha figli
INSERT INTO dbo.distinte VALUES ('C2', 'D1', 1);
INSERT INTO dbo.distinte VALUES ('C2', 'D2', 1);
INSERT INTO dbo.distinte VALUES ('C2', 'D3', 1.7);
WITH CTE_Distinte([level], padre, figlio, quantita) AS
(
/* Anchor member */
SELECT 1, padre, figlio, quantita
FROM dbo.distinte
WHERE padre = 'A1'
UNION ALL
/* Recursive member */
SELECT CTE.level + 1, D.padre, D.figlio, D.quantita
FROM dbo.distinte AS D
JOIN CTE_Distinte AS CTE
ON D.padre = CTE.figlio
)
SELECT *
FROM CTE_Distinte
ORDER BY [level];
/*
level padre figlio quantita
----------- --------------- --------------- ----------
1 A1 B1 1.000000
1 A1 B2 2.000000
1 A1 B3 1.500000
2 B2 C5 2.000000
2 B2 C2 1.000000
2 B1 C1 2.500000
2 B1 C2 5.000000
2 B1 C3 0.780000
2 B1 C4 1.250000
3 C2 D1 1.000000
3 C2 D2 1.000000
3 C2 D3 1.700000
3 C2 D1 1.000000
3 C2 D2 1.000000
3 C2 D3 1.700000
(15 row(s) affected)
*/
DROP TABLE dbo.distinte;
Per maggiori dettagli:
"Recursive Queries Using Common Table Expressions"
http://msdn2.microsoft.com/en-us/library/ms186243.aspx
>Grazie e ciao
Prego.
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org