Is it possible to make a sum of sum in one select query?
Something like this:
SELECT id, SUM(current_price - bought_price)*amount AS profit FROM purchase WHERE purchase_id = 1 GROUP BY id
I want the sum of all returned profit
This is what you are asking:
SELECT tmp.id, SUM(tmp.profit)
FROM (
SELECT id, SUM(current_price - bought_price)*amount AS profit
FROM purchase
WHERE purchase_id = 1
GROUP BY id
) AS tmp
but the result is the same as
SELECT SUM(current_price - bought_price)*amount AS profit
FROM purchase
WHERE purchase_id = 1
This is your query:
SELECT id, SUM(current_price - bought_price)*amount AS profit
FROM purchase
WHERE purchase_id = 1
GROUP BY id ;
If you want the total profit, just remove the group by and rephrase the sum():
SELECT SUM(current_price*amount - bought_price*amount) AS profit
FROM purchase
WHERE purchase_id = 1;
EDIT:
You can also write this as:
SELECT SUM((current_price - bought_price)*amount) AS profit
FROM purchase
WHERE purchase_id = 1;
By the way, the original formulation isn't correct. You want to use the same form with the group by:
SELECT id, SUM((current_price - bought_price)*amount) AS profit
FROM purchase
WHERE purchase_id = 1
GROUP BY id;
The problem with your version is that amount is taken from on arbitrary row for each id. If there is only one row in purchase for each id, then no problem. But if there are multiple rows for an id, then the query in the question will produce indeterminate results. (You are using a MySQL extension to group by that is documented here.)
SELECT id, SUM(current_price - bought_price)*amount
AS profit FROM purchase WHERE purchase_id = 1 GROUP BY id WITH ROLLUP;
You can use WITH ROLLUP modifier for GROUP BY (http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html). As result you will get all summary by product and TOTAL for all product groups.
Related
Which customer id bought maximum products? (hint : get sales by multiplying product_quantity and price_per_item fields)
SELECT
customerid,
product_quantity * price_per_item as "sales",
SUM(sales)
FROM questions
GROUP BY customerid
This is how the database looks like
After adding the sales column I am not able to perform the sum operation and getting the following error:
SELECT customerid, product_quantity * price_per_item as "sales", SUM(sales) FROM questions GROUP BY customerid LIMIT 0, 1000
Error Code: 1054. Unknown column 'sales' in 'field list'
Desired output
The exact error you are seeing is due to the product expression not appearing directly inside an aggregated function. You should have taken the sum of this product directly. You might be fine just using the following LIMIT query:
SELECT customerid
FROM questions
GROUP BY customerid
ORDER BY SUM(product_quantity * price_per_item) DESC
LIMIT 1;
If there could be multiple customers tied for top sales, then use:
SELECT customerid
FROM questions
GROUP BY customerid
HAVING SUM(product_quantity * price_per_item) = (
SELECT SUM(product_quantity * price_per_item)
FROM questions
GROUP BY customerid
ORDER BY SUM(product_quantity * price_per_item) DESC
LIMIT 1
);
You cannot use an alias created in a select clause in the same select clause, because the expressions have no order. This means, that product_quantity * price_per_item as "sales" is not necessarily executed before SUM(sales), so the DBMS tells you that sales is unknown.
You don't need the alias anyway, because with one result row per customer, what amount other than the sum would you want to show?
SELECT
customerid,
SUM(product_quantity * price_per_item) AS sales
FROM questions
GROUP BY customerid
ORDER BY customerid;
This doesn't get you the top customer, though. But your query didn't either :-) This is just an explanation what's wrong in your original query.
Here are two options on how to build up on this to get the top customer(s):
Option 1 with a subquery (a CTE here):
WITH list AS
(
SELECT
customerid,
SUM(product_quantity * price_per_item) AS sales
FROM questions
GROUP BY customerid
)
SELECT *
FROM list
WHERE sales = (SELECT MAX(sales) FROM list);
Option 2 with an analytic function:
SELECT customerid, sales
FROM
(
SELECT
customerid,
SUM(product_quantity * price_per_item) AS sales,
MAX(SUM(product_quantity * price_per_item)) OVER() AS max_sales
FROM questions
GROUP BY customerid
) with_max
WHERE sales = max_sales;
How do I get 9,300 only out of the table above? I just need to add 6500 + 1800 + 1000
Here is my current query
SELECT
SUM(e.amount) / (SELECT count(e2.receipt_no)
FROM entries e2
WHERE e2.receipt_no = e.receipt_no) as total,
e.user_id
FROM
entries e
GROUP BY e.receipt_no
The result is
Now i need to get the total per user_id
Expected output should be
From my understanding this should give you want you want
SELECT sum(DISTINCT amount) as total, reciept_no FROM entries GROUP BY receipt_no
Try some thing like this
SELECT SUM(DISTINCT(amount)) as total, user_id FROM `entries` GROUP BY user_id
Try this
SELECT SUM(amount) as total,user_id FROM entries GROUP BY user_id
First calculate DISTINCT amount group by userid,receipt_no and then sum of there entries group by user_id:
SELECT sum(total),userid from (SELECT sum(DISTINCT amount) as total,
userid,receipt_no FROM entries GROUP BY userid,receipt_no) as rgrouped
GROUP BY userid
You can also try this
SELECT user_id, SUM(DISTINCT `amount`) FROM `test` group by `user_id`
Step 1: Select distinct amount for each user id
101 - 6500,1800,1000
189 - 1019.00
Step - 2
101 = 6500+1800+1000 = 9300.00
189 = 1019.00
This will select distinct amount for each user id and then add selected amount and give you same result.
Calculate each supplier's total sales quantity and get the sales person's name if the sales person supplies parts more than 1000 units in total.
Table info:
Supplier {s_num, s_name, status, city}
Spj {s_num, p_num, j_num, qty}
This is what I have:
SELECT s_name, SUM(qty) AS sum
FROM Supplier, Spj
WHERE Supplier.s_num = Spj.s_num
AND qty > 1000
GROUP BY s_name;
I think my error is in this line:
AND qty > 1000
maybe I am using the "GROUP BY" incorrectly...
No suppliers quantity is above 800, so I get a blank result.
I want to test this:
"sum of quantity for each supplier" > 1000
Use HAVING to access aggregate results after a group by clause:
SELECT s_name, SUM(qty) AS sum
FROM Supplier, Spj
WHERE Supplier.s_num = Spj.s_num
GROUP BY s_name
HAVING qty > 1000;
See this post for more info on having vs where.
I have the following ORDERS table
I know query to select the customer that has ordered the greatest quantity. However, how would it work, if say, two customers have the same quantity. What query should I write to show both the customers?
You can use a subquery which checks that the quantity for a given record matches the largest quantity observed in the table:
SELECT *
FROM yourTable
WHERE qty = (SELECT MAX(qty) FROM yourTable)
This will return multiple records if there are more than one customer sharing the maximum quantity.
If you only wanted to get back a single record, even in the presence of ties, you could use this approach:
SELECT *
FROM yourTable
ORDER BY qty DESC
LIMIT 1
I think you want sum of qty per custNum.
If so you can try like:
select custNum,
sum(qty) as qty
from Orders
group by custNum
order by sum(qty) desc;
Fiddle here:
http://sqlfiddle.com/#!9/47931b/10
SELECT custnum,sum(qty) as total
FROM orders
group by custnum
having sum(qty) = (SELECT MAX(qty) FROM orders);
This will return both values.
I facing an issue of a way of calculating the total of the produced Amount column, so I can use it to calculate the
(user sales amount/total users sales amount) percentage ratio
SELECT * FROM Sales
ID Item Amount
5 IS1 10.00
5 IS2 2.00
3 IS1 10.00
2 IS3 7.00
9 IS5 6.00
Example 35.00
DESIRED OUTPUT
ID Amount Percentage
5 12.00 34.28571%
3 10.00 28.57142%
2 7.00 20.00000%
9 6.00 17.14285%
Example 35.00 100.0000%
SELECT ID, SUM(Amount) AS Amount
FROM Sales
GROUP BY ID
I have seen various examples on stack and other forums where people are using an additional select to calculate the total of amount column as such
SELECT ID, SUM(Amount) AS Amount,(SELECT SUM(Amount) FROM Sales) AS Total, Amount/(SELECT SUM(Amount) FROM Sales)*100 AS Percentage
FROM Sales
GROUP BY ID
But what do I do when my select query is huge, do you still put it in the select query or is there a better way this can be done.
SELECT a.ID, SUM(a.Amount) AS Amount, #rank:=#rank + 1 AS rank
FROM Sales a
INNER JOIN (SELECT #rank:=0) r
WHERE a.Item='IS1'
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount
The original query is actually longer than this, because it is also pulling in descriptions and values from other tables.
Essentially the original code of what I am doing, is going to the Sales table, pulling in all user sales data by current day, by product, by product sub_id, by transaction id. Then ranking who sold the highest amount of product, on the day, of a particular transaction id.
Of course this code gets huge, so I am not sure if it is right to add this whole code again in SELECT query to calculate a total?
Is there no way, it can calculate the total of amount without doing another query?
This will work on MSSQL, not sure about MySQL
Select distinct ID, SUM(AMOUNT) OVER (PARTITION BY ID) Amount, SUM(AMOUNT) OVER (PARTITION BY ID) / SUM(AMOUNT) OVER (PARTITION BY 1) * 100 Percentage
from Sales
order by ID
It provides you with your Desired Output as shown above.
try
declare #total_amt as decimal(18,5)
set #total_amt=(select sum(isnull(AMOUNT,0)) from Sales)
select Id,AMOUNT,(SUM(Amount)/(#total_amt)*100) as Percentage from Sales group by Id
I prefere a group by over a window function if it solves my problem:
SELECT a.ID, SUM(a.Amount) AS Amount, #rank:=#rank + 1 AS rank
, s.SumAll Total
, SUM(a.Amount)/s.SumAll*100 Percentage
FROM Sales a
, (SELECT #rank:=0) r
, (SELECT SUM(Amount) SumAll FROM Sales ) s
WHERE a.Item='IS1'
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount
Assuming sales is in reality a rather expensive view, you'll maybe better of with that (asuming mysql likes window functions):
SELECT a.ID, SUM(a.Amount) AS Amount
, #rank:=#rank + 1 AS rank
, SUM(Amount) OVER (Partition By 1) Total
, SUM(a.Amount)/SUM(Amount) OVER (Partition By 1)*100 Percentage
FROM Sales a
, (SELECT #rank:=0) r
WHERE a.Item='IS1'
AND a.tdate='2015-01-20'
GROUP BY a.ID
ORDER BY Amount
This query produces the desired output without a sub query in MySQL. SUM(Amount) OVER () gives you the total sum of Amount
SELECT ID, SUM(Amount) AS Amount,
SUM(Amount)*100/SUM(Amount) OVER () AS percentage
FROM Sales
GROUP BY ID