Query to display spent credits from transactional table

后端 未结 2 527
萌比男神i
萌比男神i 2021-02-12 21:55

I am working with a table that contains credit transactions where I want to display who\'s credits were spent when a sale is made.

In the table:

  • Cre
相关标签:
2条回答
  • 2021-02-12 22:40

    try this:

    WITH Credits_added AS (
        SELECT CreditLogId, OccurredOn, credits
        , SUM(credits) OVER (ORDER BY CreditLogId) - credits AS b --before
        , SUM(credits) OVER (ORDER BY CreditLogId) AS a --after
        , GivenByUserCode
        FROM @CreditLogs
        WHERE Credits > 0)
    , Credits_spent AS (
        SELECT CreditLogId, OccurredOn, credits
        , SUM(credits) OVER (ORDER BY CreditLogId) * -1 + credits AS b
        , SUM(credits) OVER (ORDER BY CreditLogId) * -1 AS a
        FROM @CreditLogs
        WHERE Credits < 0)
    SELECT s.CreditLogId, s.OccurredOn
    , CASE WHEN a.a > s.a THEN s.a ELSE a.a END - CASE WHEN a.b > s.b THEN a.b ELSE s.b END AS Credits 
    , a.GivenByUserCode
    FROM Credits_added AS a
    INNER JOIN Credits_spent AS s ON a.a > s.b AND s.a > a.b
    
    0 讨论(0)
  • 2021-02-12 22:51

    since you mentioned there will be 4 to 5 million records per year, even if this can be done by query it will be an slow query.

    I would suggest to have another table like creditSpent which contains (PurchaseCreditLogId , additionCreditLogId, Amount)

    And in the time of inserting purchases, find all records, calculate the amount that should be reduced from each one and store that information in that table

    Then when you are running your report you can do a simple query on this table

    0 讨论(0)
提交回复
热议问题