Skip to content
Advertisement

TSQL “where … group by …” issue that needs solution like “having …”

I have 3 sub-tables of different formats joined together with unions if this affects anything into full-table. There I have columns “location”, “amount” and “time”. Then to keep generality for my later needs I union full-table with location-table that has all possible “location” values and other fields are null into master-table.

I query master-table,

However some “location” values are dropped because sum(amount) is 0 for those “location”s but I really want to have full list of those “location”s for my further steps.

Alternative would be to use HAVING clause but from what I understand HAVING is impossible here because i filter on “time” while grouping on “location” and I would need to add “time” in grouping which destroys the purpose. Keep in mind that the goal here is to get sum(amount) in each “location”

To view the output: with the first code I get

but I want to get

Any suggestions on what can be done with this structure of master-table? Alternative solution to which I have no idea how to code would be to add numbers from the first query result to location-table (as a query, not actual table) with the final result query that I’ve posted above.

Advertisement

Answer

I can think of 2 options:

You could move the WHERE to a CASE WHEN construction:

Or you could JOIN with the possible values of location (which is my first ever RIGHT JOIN in a very long time 😉):

see: DBFIDDLE

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