Necesito descontar o descargar cantidades, tengo una consulta que arroja el siguiente resultado:
Este resultado tengo que ir descargando el saldo en base a la cantidad, la columna a calcular es descontar
; o sea para un artículo tengo una cantidad de 65 y tres saldos 50, 30 y 10 por lo tanto la columna descontar debería quedar en 50, 15 y 0, ejemplo:
El resultado del query lo puse en una tabla y lo copio a continuación:
CREATE TABLE [dbo].[prueba_descarga](
[articulo] [VARCHAR](10) NULL,
[cantidad] [DECIMAL](16, 6) NULL,
[lote] [VARCHAR](10) NULL,
[saldo] [DECIMAL](16, 6) NULL,
[fecha] [DATETIME] NULL,
[descontar] [DECIMAL](16, 6) NULL)
INSERT [dbo].[prueba_descarga] ([articulo], [cantidad], [lote], [saldo], [fecha], [descontar]) VALUES (N'A0001', CAST(65.000000 AS Decimal(16, 6)), N'452', CAST(50.0000000 AS Decimal(22, 7)), CAST(N'2018-06-07T00:00:00.000' AS DateTime), CAST(0.000000 AS Decimal(16, 6)))
INSERT [dbo].[prueba_descarga] ([articulo], [cantidad], [lote], [saldo], [fecha], [descontar]) VALUES (N'A0001', CAST(65.000000 AS Decimal(16, 6)), N'455', CAST(30.0000000 AS Decimal(22, 7)), CAST(N'2018-06-05T00:00:00.000' AS DateTime), CAST(0.000000 AS Decimal(16, 6)))
INSERT [dbo].[prueba_descarga] ([articulo], [cantidad], [lote], [saldo], [fecha], [descontar]) VALUES (N'A0001', CAST(65.000000 AS Decimal(16, 6)), N'456', CAST(10.0000000 AS Decimal(22, 7)), CAST(N'2018-06-11T00:00:00.000' AS DateTime), CAST(0.000000 AS Decimal(16, 6)))
INSERT [dbo].[prueba_descarga] ([articulo], [cantidad], [lote], [saldo], [fecha], [descontar]) VALUES (N'A0002', CAST(20.000000 AS Decimal(16, 6)), N'457', CAST(15.0000000 AS Decimal(22, 7)), CAST(N'2018-06-11T00:00:00.000' AS DateTime), CAST(0.000000 AS Decimal(16, 6)))
INSERT [dbo].[prueba_descarga] ([articulo], [cantidad], [lote], [saldo], [fecha], [descontar]) VALUES (N'A0002', CAST(20.000000 AS Decimal(16, 6)), N'458', CAST(25.0000000 AS Decimal(22, 7)), CAST(N'2018-06-11T00:00:00.000' AS DateTime), CAST(0.000000 AS Decimal(16, 6)))
Muchas gracias!!!