简体   繁体   中英

AS transaction_date created in SELECT but not found in WHERE statement, why?

I'm looking to get order data from the past 30 rolling days. The goal, eventually, is to get this to pull some DISTINCTs so I can measure new orders/customers and order/customer churn along with one-time sales (there are some subscription and some .netime products in the database).

For starters, I'm just trying to pull all orders for the past 30 days.

Here's the query.

SELECT
  CAST(creation_date_transactions_orders AS DATE) as transaction_date,
  email_contact_transactions_orders,
  title_transactions_orders,
  total_paid_transactions_orders,
  status_transactions_orders
FROM
  `nla-analytics.NLA_Keap_Keap_Keap.transactions_orders` 
WHERE total_paid_transactions_orders IS NOT NULL 
AND status_transactions_orders LIKE "PAID"
AND transaction_date BETWEEN today() AND today() - 30

That's my query.

The problem is that BQ isn't recognizing "transaction_date" in the WHERE statement. "Unrecognized name: transaction_date

Why doesn't BQ recognize the field created a few lines previous, and how do I write this correctly?

The alias created at the SELECT is not available in the WHERE in the same statement. From the docs :

The WHERE clause only references columns available via the FROM clause; it cannot reference SELECT list aliases.

You can replicate the cast in WHERE or use a subquery:

WITH transactions AS (
    SELECT
        CAST(creation_date_transactions_orders AS DATE) as transaction_date,
        email_contact_transactions_orders,
        title_transactions_orders,
        total_paid_transactions_orders,
        status_transactions_orders
    FROM
        `nla-analytics.NLA_Keap_Keap_Keap.transactions_orders` 
    WHERE 
        total_paid_transactions_orders IS NOT NULL 
        AND status_transactions_orders LIKE "PAID"
)
SELECT 
    *
FROM transactions
WHERE transaction_date BETWEEN today() AND today() - 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM