BigQuery, how to use alias in where clause?

2020-07-27 06:03发布

I have this small query, BigQuery don't recognise the alias maxdate, I am trying to return the table but only for that last date

WITH
  maxdate AS (
  SELECT
    MAX(DATE(SETTLEMENTDATE))
  FROM
    `biengine-252003.aemo2.daily`)
SELECT
  *
FROM
  `biengine-252003.aemo2.daily`
WHERE
  DATE(SETTLEMENTDATE)= maxdate

3条回答
冷血范
2楼-- · 2020-07-27 06:12

You can also do something like:

with maxdate as (
   select 
      max(date(SETTLEMENTDATE)) as mx
   from
  `biengine-252003.aemo2.daily`
)
select 
   d.* 
from `biengine-252003.aemo2.daily` d
left join maxdate on 1=1
where date(d.SETTLEMENTDATE) = maxdate.mx
查看更多
做个烂人
3楼-- · 2020-07-27 06:17

I am trying to return the table but only for that last date

Meantime, more effective way to achieve the goal is

#standardSQL
SELECT * EXCEPT(isLastDate) 
FROM (
  SELECT *, DATE(SETTLEMENTDATE) = MAX(DATE(SETTLEMENTDATE)) OVER() isLastDate
  FROM `biengine-252003.aemo2.daily`
)
WHERE isLastDate
查看更多
smile是对你的礼貌
4楼-- · 2020-07-27 06:23

You are trying to get the value of maxdate from your table maxdate. Add alias to your column and use this.

WITH
  maxdate AS (
  SELECT
    MAX(DATE(SETTLEMENTDATE)) as mx
  FROM
    `biengine-252003.aemo2.daily`)
SELECT
  *
FROM
  `biengine-252003.aemo2.daily`
WHERE
  DATE(SETTLEMENTDATE) = (SELECT mx FROM maxdate LIMIT 1)
查看更多
登录 后发表回答