SQL Server - conditional aggregation with correlation

前端 未结 2 1768
广开言路
广开言路 2021-02-07 07:02

Background:

The original case was very simple. Calculate running total per user from highest revenue to lowest:

CREATE TABLE t(Customer INTEGER  NOT NULL         


        
2条回答
  •  隐瞒了意图╮
    2021-02-07 07:43

    There is an easier solution:

    SELECT c.Customer, c."User", c."Revenue",
           1.0 * Revenue/ NULLIF(c2.sum_total, 0) AS percentage,
           1.0 * c2.sum_running / NULLIF(c2.sum_total, 0) AS running_percentage
    FROM t c CROSS APPLY
         (SELECT SUM(c2.Revenue) AS sum_total,
                 SUM(CASE WHEN c2.Revenue >= x.Revenue THEN c2.Revenue ELSE 0 END) 
                     as sum_running
          FROM t c2 CROSS JOIN
               (SELECT c.REVENUE) x
          WHERE c."User" = c2."User"
         ) c2
    ORDER BY "User", Revenue DESC;
    

    I am not sure why or if this limitation is in the SQL '92 standard. I did have it pretty well memorized 20 or so years ago, but I don't recall that particular limitation.

    I should note:

    • At the time of the SQL 92 standard, lateral joins were not really on the radar. Sybase definitely had no such concept.
    • Other databases do have problems with outer references. In particular, they often limit the scoping to one level deep.
    • The SQL Standard itself tends to highly political (that is, vendor-driven) rather than driven by actual database user requirements. Well, over time, it does move in the right direction.

提交回复
热议问题