Skip to content
Advertisement

Subtotals per category not showing data (all subtotal columns show NULL)

In my query I have one last obstacle I’m trying to overcome. My goal is to group products (“prod”) by the specified category (“prodcat”) and have a subtotal for each column’s worth of data (such as JAN, FEB etc) at the end of each category.

Below I included a link to picture of the data. It shows each column/category associated (B/O, On Hand, Commit, [Tot Avail], Jan, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV AND DEC) and a new row called ‘subtotal – prodcat’. As I said, The data associated with each prodcat needs to be subtotaled at the end of each category. As you will see in the picture, while I have the ‘Subtotal – [prodcat]’ showing up at the end of each prodcat as intended, each column’s worth of data has NULL for that row. I removed the prod names and prodcat names but you should still clearly see the issue I’m facing.

Here is a link to an example output of what is currently happening

I can’t seem to figure out what I’m doing wrong. I have tried using CASE WHEN, GROUPING SET, ROLLUP etc and has worked. For some reason, nothing I have tried thus far allows the [subtotals – prodcat] rows (and subtotal – Overall as well) to have actual values and not just NULL.

Below I went ahead and used SQL Fiddle to ‘re-create’ what I’m trying to do. The code is the same outside of fictitious data. I’ve never used SQL Fiddle before so hopefully my write up is correct. The one thing I will say is that SQL Fiddle doesn’t let you ‘create views. However I use a ‘view’ in my process so I included the code for testing purposes below and to show EXACTLY the method I am using to get my results.

Here is the query I run, once the database / tables / View are set up:

If you find my code doesn’t work, I’d be happy to run another test myself by ‘creating’ another/new DB’ with the above information and re-running the code.

Hopefully someone can help me in figuring out why the Subtotal rows are only showing NULL.

Advertisement

Answer

I figured it out. It was just a simple sum I had to do. I was overcomplicating it. For any columns I wanted to have as part of the subtotal, I just need to use sum.

When doing that as I did below:

The subtotal and Overall total populated with the data I was looking for.

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