BigQuery,如何在where子句中使用别名?

时间:2019-09-09 02:30:40

标签: sql google-bigquery

我有一个小查询,BigQuery无法识别别名maxdate,我试图返回表,但仅返回最后一个日期

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

3 个答案:

答案 0 :(得分:2)

您正在尝试从表maxdate中获取maxdate的值。将别名添加到您的列中并使用它。

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)

答案 1 :(得分:2)

  

我试图返回表格,但仅返回最后一个日期

同时,实现目标的更有效方法是

#standardSQL
SELECT * EXCEPT(isLastDate) 
FROM (
  SELECT *, DATE(SETTLEMENTDATE) = MAX(DATE(SETTLEMENTDATE)) OVER() isLastDate
  FROM `biengine-252003.aemo2.daily`
)
WHERE isLastDate

答案 2 :(得分:1)

您还可以执行以下操作:

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