1

I have the following query that returns the number of orders a stock item has had:

select count(Orders.OrderID) from Stocks, Orders
where Stocks.StockID = Orders.StockID(+) group by Stocks.StockID;

This returns:

count(Orders.OrderID)
---------------------
0
1
2
0
1
...

However, I also want to display the name of the particular stock item alongside this query. So far, I have tried this, but the following error occurs...

select Stocks.Name, count(Orders.OrderID) from Stocks, Orders
where Stocks.StockID = Orders.StockID(+) group by Stocks.StockID;

The following error occurs:

select Stocks.Name, count(Orders.OrderID) from Stocks, Orders
       *
Error: not a GROUP BY expression.

This should return:

Name        count(Orders.OrderID)
----------  ---------------------
Item1       0
Item2       1
Item3       2
Item4       0
Item5       1
.....       ...


Can anyone help? Thanks in advance.

4 Answers 4

4

It should be sth like:

select Stocks.StockID,Stocks.Name, count(Orders.OrderID) 
from Stocks
left join Orders
  on Stocks.StockID = Orders.StockID  -- explicit outer join syntax
group by Stocks.StockID,Stocks.Name;  -- matching with select column list
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much! This seems to be the simplest solution.
0

I suggest that you use the COUNT analytic function:

SELECT DISTINCT s.NAME,
       COUNT(*) OVER (PARTITION BY s.STOCKID ORDER BY s.STOCKID) AS ON_ORDER
  FROM STOCKS s
  LEFT OUTER JOIN ORDERS o
    ON s.STOCKID = o.STOCKID

dbfiddle here

Comments

0

Another option would be the following;

SELECT S.StockID, S.Name, Orders.[Count]
FROM Stocks AS S
    CROSS APPLY
    ( SELECT COUNT(*) AS [Count]
      FROM Orders AS O
      WHERE S.StockID = O.StockID
    ) AS Orders

:)

1 Comment

0

From your description, it seems that you want to report one aggregate row for each stock name, or in other words group by the stock name:

select s.name as stock_name, count(o.orderid) as orders
from   stocks s
       left join orders o
            on  o.stockid = s.stockid
group by s.name;

That will give results like

STOCK_NAME  ORDERS
----------- ------
X              123
Y               45
Z                6

You can include other columns from Stocks such as the Stock ID if you want:

select s.stockid, s.name as stock_name, count(o.orderid) as orders
from   stocks s
       left join orders o
            on  o.stockid = s.stockid
group by s.stockid, s.name;

which will give results like

STOCKID  STOCK_NAME  ORDERS
-------- ----------- ------
1        X              123
2        Y               45
3        Z                6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.