2015-12-02 67 views
0

我有這個表:執行遞歸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爲最終解決方案

+1

我不看你怎麼得到這個總和ID_Articulo = 1,您所提供的樣品臺。我也不明白爲什麼這是遞歸的? – Paddy

+0

對不起。我的錯。我編輯問題以提供更多信息。 – ericpap

+2

是的,爲什麼你的公式的1.5 * 3部分?第一行中只有1.5,其中'tipo'是2,所以根據描述,不應該包含它。你的例子只是讓你的問題不太清楚。 –

回答

4

您可以使用以下遞歸CTE來獲得預期結果:

;WITH CTE AS (
    SELECT ID_Articulo, ID_Componente, Tipo, Cantidad, 
      CAST(Cantidad AS DECIMAL(6,1)) AS partialSum 
    FROM mytable 
    WHERE ID_Articulo = 1 

    UNION ALL 

    SELECT t.ID_Articulo, t.ID_Componente, t.Tipo, t.Cantidad, 
      CAST(c.partialSum * t.Cantidad AS DECIMAL(6,1)) AS partialSum 
    FROM mytable AS t 
    INNER JOIN CTE AS c ON t.ID_Articulo = c.ID_Componente 
) 
SELECT SUM(partialSum) 
FROM CTE 
WHERE Tipo = 1 

什麼上述遞歸呢,是返回從ID_Articulo = 1發出所有分支,與Cantidad值相乘的累積產物沿着:

ID_Articulo ID_Componente Tipo Cantidad partialSum 
------------------------------------------------------------------ 
1    5    2  1.5   1.5 
1    6    1  6.0   6.0 
6    8    2  4.2   25.2 
8    9    1  2.0   50.4 
5    3    1  3.0   4.5 

結果是使用SUMpartialSum計算只有對於那些行Tipo = 1

Demo here

+1

你是男人!如何猜測需要什麼? –

+1

@GiorgiNakeuri我只是瘋狂猜測。只有OP可以驗證上述解決方案是否是他/她的真實意圖! –

+0

非常接近!我用真實的數據評估這個數據並告訴你它是怎麼回事! – ericpap