Select an excess quantity(rows) based on a total quantity from another table

Viewed 32

I'm trying to select an excess quantity (per row grouped by same Groupletter and Date) based on a total quantity of the another table. I am able to get the excess but I think it's a long code and kinda hard to understand. So I'm wondering if someone can make my code shorter and precise.

Here is my code:

IF (SELECT OBJECT_ID('tempdb..#TableA')) IS NOT NULL
DROP TABLE #TableA
GO
CREATE TABLE #TableA 
(
GroupLetter CHAR(2),
Quantity INT,
ValueDate DATE
)
INSERT INTO #TableA VALUES
('A',1,'01-02-2000'),('A',1,'01-02-2000'),('A',1,'01-02-2000'),('A',2,'01-03-2000'),('A',2,'01-03-2000'),
('B',2,'01-04-2002'),('B',2,'01-05-2002'),
('C',1,'01-02-2003'),('C',1,'01-02-2003'),('C',1,'02-02-2003'),
('D',1,'02-02-2004'),('D',1,'02-02-2004'),
('E',30,'01-02-2005'),('E',3,'01-07-2005'),('E',1,'01-02-2005'),
('F',30,'01-06-2006'),('F',15,'01-06-2006'),('F',2,'01-08-2006'),
('G',1,'01-02-2007')
;
IF (SELECT OBJECT_ID('tempdb..#TableB')) IS NOT NULL
DROP TABLE #TableB
GO
CREATE TABLE #TableB
(
GroupLetter CHAR(2),
Limit INT
)
INSERT INTO #TableB VALUES
('A',3),
('B',3),
('c',1),
('D',2),
('E',29),
('F',32),
('G',3)
;
------------------------------------------------
WITH Step1 AS 
(
SELECT  a.GroupLetter,
        a.Quantity,
        a.ValueDate,
        SUM(a.Quantity) OVER (PARTITION BY a.GroupLetter,
                                            a.ValueDate
                            ORDER BY a.Quantity DESC
                             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningQty,
        b.Limit
FROM #TableA a
JOIN #TableB b ON a.GroupLetter = b.GroupLetter
)
,Step2 AS
(
SELECT
    *,
        CASE    
            WHEN RunningQty <= Limit THEN Limit
            ELSE Limit - LAG(RunningQty,1,0) OVER (PARTITION BY GroupLetter,
                                                                ValueDate
                             ORDER BY Quantity DESC)
        END AS Qty
FROM Step1
)
,Step3 AS
(
SELECT
    *,  
        CASE
            WHEN qty <= 0
            THEN Quantity
            WHEN Quantity - qty > 0
            THEN Quantity - qty
            END AS DeniedQty
FROM Step2
)
SELECT  dg.GroupLetter,
        dg.DeniedQty,
        dg.ValueDate
FROM Step3 dg
WHERE (dg.DeniedQty > 0 AND dg.DeniedQty IS NOT NULL)

And the result is:

GroupLetter DeniedQty ValueDate
A 1 2000-01-03
C 1 2003-01-02
E 1 2005-01-02
E 1 2005-01-02
F 13 2006-01-06
0 Answers
Related