1

I need to find the Stock Item with the greatest profit margin, however am unsure on how to do so as this was calculated within the query and not taken from a table. My script is as follows (Using Oracle 11g), and currently returns several stock items when I need only one. Please help

SELECT (UPPER(Orderline.StockID) || ' ' || INITCAP(StockDesc)) AS "Item",
CategoryDesc AS "Category",
LocationCity AS "Warehouse",
Quantity AS "Number Sold",
TO_CHAR(Quantity * UnitPrice) AS "Total Income",
TO_CHAR(Quantity * UnitCost) AS "Total Cost",
TO_CHAR((Quantity * UnitPrice) - (Quantity * UnitCost)) AS "Profit"
FROM Orderline INNER JOIN 
(Stock INNER JOIN 
("CATEGORY" INNER JOIN Warehouse
ON "CATEGORY".Warehouse = Warehouse.WarehouseID)
ON Stock.ItemCategory = "CATEGORY".CategoryID)
ON Orderline.StockID = Stock.StockNo
ORDER BY ((Quantity * UnitPrice) - (Quantity * UnitCost)) DESC;
JessRap
  • 13
  • 2

1 Answers1

0

try this...

select * from (SELECT (UPPER(Orderline.StockID) || ' ' || INITCAP(StockDesc)) AS "Item",
        CategoryDesc AS "Category",
        LocationCity AS "Warehouse",
        Quantity AS "Number Sold",
        TO_CHAR(Quantity * UnitPrice) AS "Total Income",
        TO_CHAR(Quantity * UnitCost) AS "Total Cost",
        TO_CHAR((Quantity * UnitPrice) - (Quantity * UnitCost)) AS "Profit"
        FROM Orderline INNER JOIN 
        (Stock INNER JOIN 
        ("CATEGORY" INNER JOIN Warehouse
        ON "CATEGORY".Warehouse = Warehouse.WarehouseID)
        ON Stock.ItemCategory = "CATEGORY".CategoryID)
        ON Orderline.StockID = Stock.StockNo
        ORDER BY Profit DESC)
        where rownum = 1;

I've seen in the comments that you've tried rownum=1 on the inner select... This would select the only Item and sort it with order by. There's not many ways to sort a set of one element. But if you'll have sorted set of all elements, you can just pick the first. That's what happens here.


See more info about this case here.

Community
  • 1
  • 1
miracle_the_V
  • 1,006
  • 1
  • 14
  • 31