Question

I need to perform something similar like to this, the tag field will have Dynamically generated values.

Tag                     | Qty  | Price_Of_Unit
--------------------------------------------------
Jam Bottle 90ml         | 2    | $9
Jam Bottle 180ml        | 1    | $15
Jam Bottle 180ml        | 3    | $15
Jam Bottle 180ml        | 2    | $15
Jam Bottle 90ml         | 2    | $9

I want a query that returns something like this:

Tag                     | Qty  | Price_Of_Unit
--------------------------------------------------
Jam Bottle 90ml         | 4    | $9
Jam Bottle 180ml        | 6    | $15

The qty field is added while there are no repeated values for the tag field.

Not: The table has these fields from which i am generating this query

ID, Tag, QTY, Price_Of_Unit

If anyone can answer, I am desperate! Thanks In advance! Bhashithe

Was it helpful?

Solution

Do you mean you want a group by?

SELECT
    Tag
    ,sum(QTY)
    ,sum(Price_Of_Unit)
FROM
    Table
GROUP BY
    Tag

This will "group" all rows with the same tag, the other columns are functions on the group of rows - here i have chosen sum which adds together all the QTY and Price_Of_Unit columns.

Group By:

http://office.microsoft.com/en-gb/access-help/group-by-clause-HA001231482.aspx

you can do other "aggregate" functions instead of sum:

http://msdn.microsoft.com/en-us/library/office/bb177686(v=office.12).aspx

OTHER TIPS

For each tag, you are looking to sum up the Qty while also showing the individual Price_of_Unit. You'll have to go about this in a little bit of a roundabout way:

select t.Tag, sq.TotalQty, t.Price_of_Unit
from YourTable as t
inner join (
  select Tag, sum(Qty) as TotalQty
  from YourTable
  group by Tag
) as sq
on t.Tag = sq.Tag

This is because when you use grouping, SQL needs to aggregate every column that's not explicitly grouped. So, after grouping by Tag, you need to aggregate Qty (in this case by the total quantity per tag). If you were to also include Price_of_Unit in the select query with the group by clause, you would need to also aggregate that, which @gordatron has done by totalling the unit price--which as you'll agree doesn't make sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top