Join Alias Columns SQL

前端 未结 1 785
庸人自扰
庸人自扰 2020-12-07 03:00

I am trying struggling with joining alias named columns. Overall, I want an output with the with date, hour, and the actual and forecasted (most recent before 10am on the pr

相关标签:
1条回答
  • 2020-12-07 03:26

    'Date' alias can't be seen from there.

    You can use few tables after WITH, so I'll advice you to move second select there.

    I'm not completly sure about weather.meso table structure but by guesing based on your query, this should work:

    WITH
        forecast_prep AS (
            SELECT
                  date_trunc('day', foretime) :: DATE AS Foredate,
                  extract(HOUR FROM foretime) + 1     AS foreHE,
                  lat,
                  lon,
                  max(windspeed) as windspeed,
                  max(as_of)                          AS as_of
            FROM weather.forecast
            WHERE date_trunc('day', foretime) :: DATE - as_of >= INTERVAL '16 hours'
            GROUP BY Foredate, foreHE, lat, lon
       ),
       tmp AS (
          SELECT
            meso.station,
            meso.lat,
            meso.lon,
            meso.timestmp,
            date_trunc('day', meso.timestmp) :: DATE  AS Date,
            extract(HOUR FROM meso.timestmp) + 1      AS HE,
            CAST(AVG(meso.windspd) AS NUMERIC(19, 2)) AS Actual
          FROM weather.meso
          GROUP BY station, lat, lon, timestmp, Date, HE
       )
    SELECT 
        tmp.station, tmp.Date, tmp.HE, tmp.Actual, forecast_prep.windspeed, forecast_prep.as_of
    FROM tmp
    INNER JOIN forecast_prep ON (
        tmp.lat = forecast_prep.lat 
        AND tmp.lon = forecast_prep.lon 
        AND tmp.Date = forecast_prep.Foredate
        AND tmp.HE = forecast_prep.foreHE
    )
    WHERE 
        (tmp.timestmp BETWEEN '2016-02-01' AND '2016-02-02') 
        AND (tmp.station = 'KSBN')
    GROUP BY 
        tmp.station, tmp.Date, tmp.HE, forecast_prep.windspeed, forecast_prep.as_of, tmp.Actual
    ORDER BY tmp.Date, tmp.HE ASC;
    

    Like in first example right here https://www.postgresql.org/docs/8.4/static/queries-with.html

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