简体   繁体   中英

BigQuery: Use CAST, GROUP BY, and HAVING

I am trying to use HAVING after a GROUP BY but I get this error:

SELECT list expression references sales_order.SalesOrderDateTime which is neither grouped nor aggregated at [2:8]

The field is in the SELECT list, and GROUP BY, but it is part of a CAST because I do not want the timestamp part of the datetime. It works without the CAST on another table where the format is already YYYY-MM-DD. It really should work here as well. Is there a way around this?

I tried using STRING FORMAT 'YYYY-MM-DD' but that does not work either.

SELECT 
  CAST(sales_order.SalesOrderDateTime AS DATE) as created_at,
  sales_order.SalesOrderNo as order_id,
  sales_order.SellToEmail as customer_email,
  sum(sales_order_item.OriginalPrice)*100 as total_amount_cents,
  max(sales_order.TotalDiscountAmount)*100 as discount_amount_cents
FROM `my_dw.external_datamart_1.SalesOrder_view` 
WHERE CAST(sales_order.SalesOrderDateTime AS DATE) >= '2022-01-01'
GROUP BY CAST(sales_order.SalesOrderDateTime AS DATE), sales_order.SalesOrderNo, sales_order.SellToEmail
-- This does not work with CAST
HAVING sum(sales_order_item.OriginalPrice) > max(sales_order.TotalDiscountAmount)
LIMIT 1000
)

A CTE works of course, but I would like to avoid that if possible.

You can try this:

group by 1,2,3

instead of using full expressions.

I face the same issue time to time in my complex queries. I think it's a bug and can be reported here https://issuetracker.google.com/

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