标准SQL日期功能

时间:2019-01-08 17:35:21

标签: sql google-bigquery standard-sql

我正尝试迁移到Standard SQL并阅读一些有关日期函数的文档,但对于如何执行特定查询我还是有些困惑。

我当前的旧版SQL查询如下:

legacySQL

select
date,
round(sum(revenue_total),2) as revenue
from [project:dataset.table]
where month(date) = month(date_add(current_date(),-1,'month'))
group by 1

如何将where语句转换为标准SQL查询?

4 个答案:

答案 0 :(得分:1)

您可能想要:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<li class="nav-item">
  <div class="dropdown">
      <a href="#"
         class="nav-link dropdown-toggle a-btn ltc-gold-web-golden"
         data-toggle="dropdown" aria-expanded="false">Characters</a>
      <ul class="dropdown-menu" role="menu">
          <li class="nav-item">
              <a href="ron.html"
                 class="nav-link a-btn ltc-gold-web-golden">Ron</a>
          </li>
          <li class="nav-item">
              <a href="fatima.html"
                 class="nav-link a-btn ltc-gold-web-golden">Fatima</a>
          </li>
          <li class="nav-item">
              <a href="kandice.html" class="nav-link a-btn ltc-gold-web-golden">Kandice</a>
          </li>
          <li class="nav-item">
              <a href="ricky.html"
                 class="nav-link a-btn ltc-gold-web-golden">Ricky</a>
          </li>
          <li class="nav-item">
              <a href="rob.html" class="nav-link a-btn ltc-gold-web-golden">Rob</a>
          </li>
      </ul>
  </div>
</li>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

我怀疑您的WHERE DATE_TRUNC(date, MONTH) = DATE_TRUNC(CURRENT_DATE(), MONTH) 列实际上是date类型,在这种情况下,您需要先转换为TIMESTAMP

DATE

请注意,WHERE DATE_TRUNC(EXTRACT(DATE FROM date), MONTH) = DATE_TRUNC(CURRENT_DATE(), MONTH) 函数具有一个可选的EXTRACT子句,如果您不想使用默认时间UTC,则该子句可用于指定要使用的时区。有关更多信息,请参见timestamp function documentation

答案 1 :(得分:0)

关于手头的日期函数,BG's standard SQL中有等效的函数

  • MONTH()-> EXTRACT():EXTRACT(part FROM date_expression),例如

    EXTRACT(MONTH FROM date)
    
  • date_add()current_date()仍然可用。

答案 2 :(得分:0)

下面是使用GitHub公共存储库的示例:

SELECT
  CAST(committer.date AS DATE),
  COUNT(*)
FROM
  `bigquery-public-data.github_repos.commits`
WHERE
  EXTRACT(MONTH FROM CAST(committer.date AS DATE)) = EXTRACT(MONTH FROM (DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)))

GROUP BY
  1
LIMIT
  10

答案 3 :(得分:0)

我猜你真的想要:

where date_trunc(date, 'month') = date_add(date_trunc(current_date), interval -1 month)

但是,您所写的内容并未考虑年份,因此应该是:

where extract(month from date) = extract(month from current_date) - 1