MySQL - alternatives to nested subqueries when limiting aggregate data in a correlated subquery

前端 未结 1 956
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 06:55

I have a table that looks something like this:

DataTable
+------------+------------+------------+
| Date       | DailyData1 | DailyData2 |
+------------+----         


        
1条回答
  •  迷失自我
    2021-01-20 07:17

    No, you can't use correalted subqueries in the FROM clause. But you can use them in the ON conditions:

    SELECT AVG(d.DailyData1) Data1_20DayAvg 
           --- other aggregate stuff on d (Datatable)
    FROM 
          ( SELECT '2012-01-23' AS DateChecked
          ) AS dd
      JOIN
          DataTable AS d
        ON
          d.Date <= dd.DateChecked
        AND
          d.Date >= COALESCE( 
          ( SELECT DailyData1 
            FROM DataTable AS last20 
            WHERE Date <= dd.DateChecked 
              AND (other conditions for last20)
            ORDER BY Date DESC 
            LIMIT 1 OFFSET 19
          ), '1001-01-01'   )
    WHERE (other conditions for d Datatable)
    

    Similar, for many dates:

    SELECT dd.DateChecked 
         , AVG(d.DailyData1) Data1_20DayAvg 
           --- other aggregate stuff on d (Datatable)
    FROM 
          ( SELECT DISTINCT Date AS DateChecked
            FROM DataTable 
          ) AS dd
      JOIN
          DataTable AS d
        ON
          d.Date <= dd.DateChecked
        AND
          d.Date >= COALESCE( 
          ( SELECT DailyData1 
            FROM DataTable AS last20
            WHERE Date <= dd.DateChecked 
              AND (other conditions for last20)
            ORDER BY Date DESC 
            LIMIT 1 OFFSET 19
          ), '1001-01-01'   )
    WHERE (other conditions for d Datatable)
    GROUP BY 
          dd.DateChecked 
    

    Both queries assume that Datatable.Date has a UNIQUE constraint.

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