SQL query to find sum using group by - sql

SQL query to find sum of quantity of similar prodid only if quantity in each prodid greater than 1.
SQL query:
Select ProdID,sum(quantity)
From product
Where quantity >1
Group by ProdID
What logical error in above query ??
The Result should be :
ProdID Quantity
------ --------
102 11

For such purpose include also quantity column in the group by expression with having clause
Select ProdID,quantity
from product
group by ProdID, quantity
having sum(quantity) >1
Edit ( due to your last comment ) : Use not in as below
Select ProdID, sum(quantity)
from product
where ProdID not in ( select ProdID from product p where quantity = 1 )
group by ProdID
Rextester Demo

You can use filtering in the having:
Select ProdID, sum(quantity)
from product
group by ProdID
having min(quantity) > 1;
The use of min() assumes that quantity is non-negative.

Related

Get the date for each duplicated row in SQL Server

I've made a query to get how many products are sold more than one time and it worked.
Now I want to show the transaction date for each of these duplicated sales, but when I insert the date on the select it brings me a lot less rows: something is going wrong. The query without the date returns 9855 rows and with the date just 36 rows.
Here is the query I'm doing:
SELECT TransactionDate,
ProductName,
QtyOfSales = COUNT(*)
FROM product_sales
WHERE ProductID = 1 -- Product Sold ID
AND ProductName IS NOT NULL
GROUP BY ProductName,
TransactionDate
HAVING COUNT(*) > 1
Perhaps a subquery? Can you help in that regard?
You can use the corresponding COUNT window function, that will find the amount of transactions by partitioning on the "ProductName" as required:
WITH cte AS(
SELECT TransactionDate,
ProductName,
COUNT(*) OVER(PARTITION BY ProductName) AS QtyOfSales
FROM product_sales
WHERE ProductID = 1 -- Product Sold ID
AND ProductName IS NOT NULL
)
SELECT DISTINCT TransactionDate,
ProductName
FROM cte
WHERE QtyOfSales > 1

Which store type sells the maximum products by the value of sales amount & by quantity sold

I have to use only single SELECT statement. Multiple select statements are not allowed.
I have a table named "Transactions" which has the following variables:
Qty - It has total Quantities ordered for a particular product
total_amt - It has Amount paid by customers for the particular products
Store_type - It has transaction channels
For example, if Qty ordered are 5 and price of each quantity of product is 100. then total_amt would be carrying 500.
Now I have to find the Store type that sells the maximum products by the value of sales amount & by quantity sold. I have to do this using sub queries in Having clause.
I have written the following code in SQL Server but it is not giving me any output and throwing the error that Transactions.total_amt should be included in having clause or aggregated function. On using total_amt in group by, I am not getting any result in the output.
Below is the query which I have written :
select store_type, MAX(total_amt), MAX(Qty)
from Transactions
group by Store_type
Having total_amt = (select SUM(total_amt) from Transactions group by Store_type)
AND
Qty = (select SUM(Qty) from Transactions group by Store_type)
A simple way is based on max order by and limit
select store_type, MAX(total_amt), MAX(Qty)
from Transactions
group by Store_type
ORDER BY MAX(total_amt) DESC, MAX(Qty) DESC
LIMIT 1
Check both query result and identify store type wise total amt and max total amt matching with qty or not.
If you want only matched then you can create 2 sub query tables and use inner join.
I hope this will resolve.
select
Store_type,
SUM(total_amt) AS Total_total_amt,
SUM(Qty) AS Total_Qty
from Transactions
group by Store_type
select
store_type,
MAX(total_amt) AS max_total_amt,
MAX(Qty) AS max_Qty
from Transactions
group by Store_type
You can use a query as shown below
;With cte as
(
Select sum(qty) as sum_quantity,sum(sales) as sum_sales,store_type
From transaction
Group by store_type
)
Select Max(sum_quantity),max(sum_sales),store_type from cte
Group by store_type
Select store_type
From transactions
Where total_amt > 0 and qty>0
Group by store_type
Order by sum(total_amt) desc,sum(qty) desc ;

SQL divide the column values to equal groups with ntile

I need to write sql query that divide the products to 3 equal groups by their price, (The cheapest products will be in the first group). For each group I have to present the price ranges it includes and the average units in stock.
I try to use ntile but I got stuck:
SELECT UnitPrice, NTILE(3) OVER (
ORDER BY UnitPrice ASC
) AS productGroup, UnitsInStock
FROM Products
You need to put a query on top of this one. Something like this:-
select productGroup, min(UnitPrice), max(UnitPrice), avg(UnitPrice)
from (
SELECT UnitPrice, NTILE(3) OVER (ORDER BY UnitPrice ASC) AS productGroup
, UnitsInStock
FROM Products
) t1
group by productGroup

SQL Query: SELECT MAX SUM quantity

How do i combine a SUM and MAX in a single query?
Lets say i have a orderrule:
ProductID \ Quantity
I Could say:
Select ProductID,SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
ORDER BY SUM(Quantity) Desc
However that would return all sales, and not just the most sold product (with quantity).
Try this
SELECT TOP(1)
*
FROM
(
Select
ProductID,
MAX(Quantity) As MaxQuantity,
SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
)AS X
ORDER BY Sold DESC
So there are two ways to do it - first to have a limit on the number of results, something likes:
select * from (your_select) where rownum = 1
the other one is to pick the one with the the highest value, which will require a subselect, something like:
having sum(quantity) =
(select max(sum_quan) from (select sum(Quantity) from orderrule group by Product_id))
SELECT TOP 1 ProductID, Sold FROM
(
SELECT ProductID, SUM(Quantity) AS Sold
FROM Orderrule
GROUP BY ProductID
) totals
ORDER BY Sold DESC

SQL GROUP BY on a sub query

I have a query that will return results from 2 tables into 1 using a UNION ALL, which all works as I need it to. However I need to run a GROUP BY and an ORDER BY on the returned dataset however I am getting many errors and I'm not sure how to solve it.
Here is my Query:
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
This will return a results set such as this:
ProductID Quantity
15 2
20 2
15 1
8 5
5 1
I then want to run a GROUP BY on the ProductID field and then finally an ORDER BY DESC on the Quantity field. So in the final output, this particular results set will finally result in this:
ProductID
8
15
20
5
I can then run queries on this result set as I usually do
EDIT:
As stated above, but maybe not implied enough is that I will need to run queries on the returned results, which isn't working as you cannot run a query on a set of results that have an ORDER BY clause (so far as I gathered from the error list)
If you want more information on the problem, here it is:
From this results set, I want to get the products from the product table that they relate to
SELECT * FROM Products WHERE ID IN (
SELECT ProductID
FROM
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
ORDER BY SUM(Quantity) DESC
)
However, I get this error: The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
The output of products need to be in the order that they are returned in the sub query (By quantity)
SELECT Products.*
FROM Products
INNER JOIN
(
SELECT ProductID, Sum(Quantity) as QuantitySum
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) v
GROUP BY ProductID
) ProductTotals
ON Products.ID = ProductTotals.ProductID
ORDER BY QuantitySum DESC
will this work?
SELECT ProductID
from
(
SELECT ProductID, Quantity
FROM BasketItems
UNION ALL
SELECT ProductID, Quantity
FROM OrderItems
) temp
GROUP BY temp.ProductID
ORDER BY SUM(temp.Quantity) desc
Here's a cte version (no live test so please excuse blunders)
EDIT
;WITH myInitialdata_cte(ProductID,Quantity)
AS
(
SELECT ProductID, Quantity FROM BasketItems
UNION ALL
SELECT ProductID, Quantity FROM OrderItems
)
SELECT b.ID
FROM
myInitialdata_cte a
INNER JOIN Products b ON
a.ProductID = b.ID
GROUP BY ProductID
ORDER BY SUM(a.Quantity) DESC