Skip to content
Advertisement

SQL summing the same column with different date conditions

I’m using one table and am trying to sum total spend for two separate years, pulling from the same column.

Essentially I have a list of customers, and I’m trying to sum their 2018 spend, and their 2019 spend. I’ve tried a few different things, but I can’t seem to get the “case when” function to work because once the 2018 spend condition is met and that value is populated, it won’t sum for 2019, and vice versa—so I’ve got a total for 2018 OR 2019, but no customers are showing spend for both.

This is my query:

Any idea what I’m doing wrong? Thank you!

Advertisement

Answer

I really doubt that your problem is with SQL syntax or a bug. Your query looks like it should be doing what you want.

The issue is that those fields are not the same for any customer in the two years. Try something like this:

I speculate that last names are unlikely to change. If this works, you can start adding columns back to see where the problem columns are.

This is why databases are normalized. Repeated data tends to get out of synch.

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