简体   繁体   中英

Google BigQuery SQL create multiple "columns" depending on if/then statement?

Is this possible to do in a single query?

I have a sales table that I want to query. The table has details of our sales transactions at the item level, so each record contains fields like: cust_no , item_no , amount , month , year .

I want to summarize the sales info by customer by month by year. I know I can summarize the data like this:

select cust_no,
fiscal_year,
month,
sum(amount) as totalAmt,
group by cust_no, month, fiscal_year

...to get something like this:

cust_no month fiscal year totalAmt
cust_123 1 2022 123.45
cust_345 1 2022 456.78

But I'd like to split out the sales amount depending on whether or not the item_no field is empty or not (because "products" have an item_no where as "services" have a blank item_no).

This is the result I'm going for:

cust_no month fiscal year totalAmt where item_no != '' totalAmt where item_no = ''
cust_123 1 2022 123.45 222.22
cust_345 1 2022 456.78 111.11

Is there a way to do this in a single query?

May be you can try following query.


select 
    cust_no,
    fiscal_year,
    month,
    SUM(CASE WHEN item_no is NOT NULL THEN totalAmt ELSE 0 END) as total_amt_when_non_null,
    SUM(CASE WHEN item_no is NULL THEN totalAmt ELSE 0 END) as total_amt_when_null
FROM table
group by cust_no, month, fiscal_year

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-2025 STACKOOM.COM