我有這個表:執行遞歸SQL查詢(SQL Server 2005中)
ID_Articulo ID_Componente Tipo Cantidad
1 5 2 1.5
5 3 1 3
1 6 1 6
2 3 1 3.5
6 8 2 4.2
8 9 1 2
我需要找到Cantidad字段的總和對於一個給定ID_Articulo和TIPO = 1。例如,對於ID_Articulo = 1應該是1.5 * 3 + 6 + 6 * 4.2 * 2 = 60.9。
每個ID_Articulo的級別(深度)數量是可變的。
這可以用SQL查詢嗎?我的數據庫是SQL Server 2005中
aditional的信息
場ID_Articulo和ID_Compenente都與同一個表Articulos。這就是爲什麼數據是遞歸的。因此,對於給定的例子,我有:
ReC#1 is not Tipo=1, but relates ID 1 with ID 5
ReC#2 relates ID 5 with ID 3 and Tipo=1 So, I have 1.5 (of ReC#1) * 3
ReC#3 relates ID 1 with ID 6 and Tipo=1, so i have 6
ReC#4 is from another ID
ReC#5 relates ID 6 with ID 8 but Tipo!=1 so i don't sum
ReC#6 relates ID 8 and ID 9 and Tipo=1, so I have 6 * 4.2 * 2
最終解決
這是最後的代碼(有些字段名稱不同):
;WITH CTE AS (
SELECT b.ID_Articulo, ID_Componente, Tipo, Cantidad,
CAST(Cantidad AS DECIMAL(6,2)) AS partialSum
FROM Arbol b inner join articulos a on a.ID_Articulo=b.ID_Componente
WHERE b.ID_Articulo = 2716
UNION ALL
SELECT t.ID_Articulo, t.ID_Componente, t.Tipo, t.Cantidad,
CAST(c.partialSum * t.Cantidad AS DECIMAL(6,2)) AS partialSum
FROM (SELECT b.ID_Articulo, ID_Componente, A.Tipo, Cantidad FROM Arbol b inner join articulos a on a.ID_Articulo=b.ID_Componente inner join Articulos a2 on a2.ID_Articulo=b.ID_Articulo where a2.Tipo<>'I') as t
INNER JOIN CTE AS c ON c.ID_Componente = t.ID_Articulo
)
SELECT SUM(partialSum)
FROM CTE
WHERE Tipo = 'I'
感謝@ giorgos,betsos爲最終解決方案
我不看你怎麼得到這個總和ID_Articulo = 1,您所提供的樣品臺。我也不明白爲什麼這是遞歸的? – Paddy
對不起。我的錯。我編輯問題以提供更多信息。 – ericpap
是的,爲什麼你的公式的1.5 * 3部分?第一行中只有1.5,其中'tipo'是2,所以根據描述,不應該包含它。你的例子只是讓你的問題不太清楚。 –