sql >> Database teknologi >  >> RDS >> Mysql

MySQL - alternativer til indlejrede underforespørgsler ved begrænsning af aggregerede data i en korreleret underforespørgsel

Nej, du kan ikke bruge korrealiserede underforespørgsler i FROM klausul. Men du kan bruge dem i ON betingelser:

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)

Tilsvarende for mange datoer:

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 

Begge forespørgsler antager, at Datatable.Date har en UNIQUE begrænsning.




  1. Sådan importeres Room Persistence Library til et Android-projekt

  2. Konfiguration af databasemail i SQL Server

  3. Hvordan får jeg tid fra DateTime-format i SQL?

  4. Flet to tabeller i én SQL-forespørgsel og gør datoværdierne unikke