Reputation: 3854
I have a orders table that have order detail and the column named Category where Category is the type of order.
Now the customer can search the order details.
Now what i want to write a query the show the order details and a column called TotalOrder that will show the TotalOrders placed by all customers for that category,
Example Say the Order Table like
OrderID CustomerID OrderDetails Category
1 1 test A1
2 1 test1 A2
3 2 test3 A2
4 3 test4 A2
So if query for the order id 1
It will result like with Order ID 2
OrderID Cust_ID OrderDetails Category TotalOrdersInThisCategory
2 1 test A2 3
This scenario is a demonstration of the actual problem.
How can i achieve this?
Do i need to fetch the Order detail in one query and Another query with group by Category clause and then make a inner join. Any better ideas is appreciable.
The order details will have few millions of records.
Please Suggest Some Better Title of this question
Any help is appreciated
Upvotes: 1
Views: 519
Reputation: 8709
SELECT
OrderID,
Cust_ID,
OrderDetails,
Category,
(select count(*) from orders where category = o.category) TotalOrdersInThisCategory
FROM
Orders o
or you could try this:
SELECT
o.OrderID,
o.Cust_ID,
o.OrderDetails,
o.Category,
c.TotalOrdersInThisCategory
FROM
Orders o
INNER JOIN (select category, count(*) from orders group by category) c
ON o.Category = c.Category
Upvotes: 0
Reputation: 70638
You can try this and see if it runs better:
SELECT *
FROM ( SELECT *, COUNT(*) OVER(PARTITION BY Category) TotalOrdersInThisCategory
FROM OrderTable) A
WHERE OrderId = 2
Upvotes: 2