sql >> Base de Datos >  >> RDS >> Sqlserver

Seleccionar consulta de asignación de SQL

Prueba esto:

;WITH Subtotals
AS
(
  SELECT
    T1.Id, T1.CodeId, SUM(T2.Value) SubTotal  
  FROM Tb1 T1
    JOIN Tb1 T2
       ON T1.CodeId = T2.CodeId
         AND T1.Id >= T2.Id
  GROUP BY T1.Id, T1.CodeId
)
SELECT
    S.ID,
    S.CodeID,
    T1.Value,
    CASE WHEN T2.value >= S.Subtotal
         THEN T1.value
         ELSE T1.value - (S.Subtotal - T2.value)
    END UsedValue,
    T2.Value T2Value
FROM Subtotals S
   JOIN Tb2 T2
      ON S.CodeId = T2.CodeId
   JOIN Tb1 T1
      ON S.Id = T1.Id
WHERE T2.Value >= S.SubTotal - T1.Value

Ver resultado en SQL FIDDLE