Skip to content
Advertisement

MySQL – GROUP BY not working with multiple CASE WHEN statements

I am working on a database with Kickstarter database, and I’m trying to:

  1. Define short, medium-lengthed, and long campaigns
  2. See how much each length of campaign raise
  3. Convert different currencies into USD

My original code is as follows:

I’m expecting a result of:

Where XXXXXX is the aggregate of the pledged amount after conversion. The original code shows:

So I improvised by adding additional GROUP BY, after realizing I can’t GROUP BY Amount Raised:

But the result is instead not grouping as I intended:

I’ve tried many ways, but couldn’t find a solution

Advertisement

Answer

You need to move the case expression on the currency name within the aggregate function:

Other things to note:

  • don’t use single quotes for column identifiers – they are meant for literal strings (MySQL wants backticks instead); matter of fact, it is just simpler to use identifiers that do not require quoting

  • both case expressions can be simplified, as shown above; in the first one, there is no need to check that the duration of the campaign is greater than 30 in the second branch (the first branch traps that already); in the second one, you can use the short-circuit form instead of repeating the column name in each branch

  • table aliases make the query easier to write and read

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement