Skip to content
Advertisement

How to Group By in SQL Server Query

I’m using this query to get the Sum of SaleAmount for each type (SOType) of Sale Invoices.
I am getting the result but the result is not grouped by SOType. Have tried to use Group by Outside the query after where condition but getting an error as

“Column ‘SaleInvoices.InvoiceID’ is invalid because it is not contained in either aggregate or group by function”.

enter image description here

Advertisement

Answer

You want conditional aggregation. The logic should look something like this:

I’m not sure I got the arithmetic correct.

Notes:

  • The group by clause defines the rows being returned by the query. If you want one row per SOType then you want to GROUP BY SOType.
  • Use date comparisons and functions for dates. It is absurd to convert a date to a string to compare to a date.
  • You probably don’t need COALESCE() or ISNULL() to handle NULL values. These are generally ignored by aggregation functions.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement