Mehboob Afridi
Mehboob Afridi

Reputation: 309

Select Count from multiple columns and multiple tables group by one column

I am stuck with an MS Access 2003 query. I have been googled and read many similar questions but I couldn't reach to a desire result.

I have two tables "Orders" and "Inventory"

           Orders                              Inventory
----------------------------------------    | -------------------
| SKU         | OrderID |PStatus    |   |   | SKU  | LID  |
----------------------------------------|   | -------------------
|  23|        | abc     |  New      |       |  23  | wsx  | 
|  24|        | asd     |  Shiped   |   |   |  24  | qax  | 
| 19 |        | zxc     |  New      |   |   |  19  | wsx  |
----------------------------------------    | -------------------

Question: I want query like

SELECT Orders.SKU, 
       Count(LID), 
       LID 
FROM Orders 
INNER JOIN Inventory on Orders.SKU=Inventory.SKU 
WHERE Orders.PStatus = 'New' 
AND (OrderID = 'abc' OR Order = 'zxc')

This might be a very basic query but I am new to this so any example would be much appreciated.

Upvotes: 1

Views: 1298

Answers (1)

dash
dash

Reputation: 91480

Looking at your example above, I'd say using a simple 'Group By' should be good enough.

SELECT      Orders.SKU, 
            LID,
            COUNT(LID),

FROM        Orders 
INNER JOIN  Inventory on Orders.SKU=Inventory.SKU 
WHERE       Orders.PStatus = 'New' 
AND         (OrderID = 'abc' OR Order = 'zxc')

GROUP BY    Orders.SKU,
            LID

What we are really saying is load all of the SKU's from the orders table that have a matching LID in the inventory table. We then ask for a count for each of those order-LID combinations (number of LID's per SKU basically) - the GROUP BY tells Access that it should count the rows based on the number of times each combination of SKU and LID appear.

Upvotes: 2

Related Questions