简体   繁体   中英

Sum case when like then

I am using a dataset on BigQuery and essentially I would like to pull a table to show the total volume of liters sold per month of a specific year. This is currently what I have written:

SELECT 
SUM( CASE WHEN `date` LIKE '2012-01-%' THEN `volume_sold_liters` END) as Jan_Total
FROM `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

This is the error message I am also getting:

No matching signature for operator LIKE for argument types: DATE, STRING. Supported signatures: STRING LIKE STRING; BYTES LIKE BYTES at [2:16]

I understand that the error message is asking for me to change the string to a date but how do I do that? I have multiple dates in the same month that I want added together. I tried to switching the date to a string instead and I get NULL in my table.

What am I doing wrong? Is there a better way to go about pulling the table I want?

You can use the dedicated date functions offered by BigQuery in your case. Since you want the month part of the purchased date you can consider something like the query below

SELECT
  SUM(CASE
          WHEN DATE_TRUNC(purchase_date, MONTH) = '2022-01-01' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

The error you get is because you try to compare a DATE to a STRING. To fix this you could go for

SELECT
  SUM(CASE
          WHEN CAST(purchase_date AS STRING) LIKE '2022-01-%' THEN volume
          ELSE 0
      END
    ) AS Jan_Total
FROM
  `personal-projects-340200.Iowa_liquor_cedar_rapids.store_3`

But it's better to use date functions when manipulating dates.

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