I have a table which looks like this:
Name | Quantity | Unit -------+-------------+---------- Water 10 Lt Water 5 Lt Water 3 Lt Snacks 20 Kg Snacks 15 Kg Beer 7 Lt Beer 12 Lt Pizza 1 Piece Pizza 2 Piece Pizza 5 Piece
I need to get these results:
Name | Quantity_Unit -------+------------------ Water 18 Lt Snacks 35 Kg Beer 19 Lt Pizza 8 Piece
So I need to select sum of quantities by products AND add unit of measure in the same column. It is pretty simple and that’s how I do it:
select name, cast(sum(quantity) as nvarchar) + ' ' + max(unit) as total from goods group by name
My question is how can I add units of measure to aggregated column with sum(quantity) not using aggregate functions like max(unit) or using max() is fine for this case? Basically all goods in group by will have the same unit of measure and I’m looking for most elegant query. Thanks.
In your case, you can either use MAX or MIN and it would not make any difference for your result.
You can also avoid the aggregate functions MAX and MIN by just querying column
unitand adding the same ingroup byclause as well.