Averaging Grouped Data in Single SQL Statement Using Multiple Group Bys - sql

I want to see the average cost of an item. First I am using a SUM statement and GROUP BY the manufacturing order and Item to see how much each item costs per manufacturing order (using WHERE statements to take out specific steps in the process). Then I want to average those to see how much the item costs on average based on that set, can I do this easily in one statement instead on creating a temp table?

You have to take result in temp table if you first want to sum the cost of an item per manufacture order and perform average on total cost per item achieved from sum. I hope I understood your problem statement clearly.
SELECT item, AVG(cost) FROM
(SELECT item, manufacture_order, SUM(COST) cost
FROM manufacture_order_tab
GROUP BY item, manufacture_order) tab1
GROUP BY item;

try this
SELECT AVG(Cost), SUM(COST)
FROM your_table
GROUP BY your_column

Related

Grouping ORDER ITEMS from hourly to daily

I would like to SUM the price of these Order Items together for each Order for a Contract.
I want to reduce my granularity from hourly to daily and so reduce the row count that we pass to the fact table and then the SSAS cube.
i.e. Contract A which can have many Orderlines, consider Orderline 1 which can have many Order Items.
I have had to screen the Order Items, but they are just sequential id numbers.
The problem is that I have to roll this up to a daily granularity from hourly, but still be able to give users on the cube access to the Order Item level
you can use SUM as a window function. this will effectively write the same sum to multiple rows for each order-item; just like the price.
for example
SELECT ......
, SUM(price) OVER (PARTITION BY order_item)
....
FROM ....
GROUP BY ....

Bigquery - how to aggregate data based on conditions

I have a simple table like the following, which has product, price, cost and category. price and cost can be null.
And this table is being updated from time to time. Now I want to have a daily summary of the table content grouped by category, to see in each category, how many products that has no price, and how many has a price, and how many products has a price that is higher than the cost, so the result table would look like the following:
I think I can get a query running everyday by setting up query re-run schedule in bigQuery, so I can have three rows of data appended to the result table everyday.
But the problem is, how can I get those three rows? I know I can group by, but how do I get the count with those conditions like not null, larger than, etc.
You seem to want window functions:
select t.*
countif(price is nuill) over (partition by date) as products_no_price,
countif(price <= cost) over (partition by date) as products_price_lower_than_cost
from t;
You can run this code on the table that has date column. In fact, you don't need to store the last two columns.
If you want to insert the first table into the second, then there is no date and you can simply use:
select t.*
countif(price is nuill) over () as products_no_price,
countif(price <= cost) over () as products_price_lower_than_cost
from t;

How to select MAX from AVG?

I'm practicing for my SQL exam and I can't figure out the following question:
"Of the average amount paid per customer, show the highest amount."
So to retrieve the average amount paid, I would do the following:
SELECT AVG(Amount) AS 'Average amount paid'
FROM Payment;
Then I would like to retrieve the highest average amount out of this list of averages. I thought the following would do the trick:
SELECT MAX(AVG(Amount)) AS 'Highest average amount paid'
FROM Payment;
This doesn't seem to work. I get the following error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
I would like some help with this. What is the correct way to approach this? Thank you in advance.
In SQL Server, you can order the records and use TOP 1 to keep only the record that has the highest amount:
SELECT TOP 1 Customer_id, AVG(Amount) AS [Average amount paid]
FROM Payment
GROUP BY customer_id
ORDER BY [Average amount paid] DESC;
Note: for this query to make sense, you need a GROUP BY clause. Without it, it would just return one record, with the average of payments within the whole table.
Try using a sub-query:
SELECT MAX(src.cust_avg) AS "Highest average amount paid"
FROM (
SELECT cust_id, AVG(Amount) AS cust_avg
FROM Payment
GROUP BY cust_id -- Get averages per customer
) src
;
To get the "per customer" averages first, you need include something like GROUP BY cust_id.
SQL Fiddle
Use order by:
select customer, avg(amount)
from payment
group by customer
order by avg(amount) desc
fetch first 1 row only;
The fetch first (although standard) is not supported by all databases, so you should use the version appropriate for your database.
In SQL Server, you would use either select top (1) or offset 0 fetch first 1 row only (the offset is not optional, alas).
There are also databases where avg() on an integer returns an integer. If amount is an integer and your database does this, then use avg(amount * 1.0).

Whats the difference between these two SQL queries?

Question: Select the item and per unit price for each item in the items_ordered table. Hint: Divide the price by the quantity.
1.
select item, sum(price)/sum(quantity)
from items_ordered
group by item;
2.
select item, price/quantity
from items_ordered
group by item;
Have a look at the resultis for flashlights. First one shows average price correctly but 2nd one only takes 28/4 and shows 7, ignoring the 4.5 few rows down. Someone please explain why this is the case.
The used table data from an external website.
SUM() is a group function - so that essentially says go get me all the price and quantities by item, and add them all up to return them in one row.
MySQL is quite forgiving when grouping things and will try to retrieve a rowset (which is why your second example returns something - albeit wrong).
Generally, if you are GROUPing columns (items in your exmaple), you need to return one row per column (item).
Try running the SQL below to see what that looks like.
SELECT item
, SUM(price) AS sum_price
, SUM(quantity) AS sum_quantity
, COUNT(*) AS item_count
, SUM(price) / SUM(quantity) AS avg_price_per_quant
FROM items_ordered
GROUP BY item
ORDER BY item ASC
The first query returns the average price for that item, the second query returns the price for the first item it encounters. This only works in MySQL, the second query would error in SQL Server as no aggegrate function is used. See this post for more details Why does MySQL allow "group by" queries WITHOUT aggregate functions?.

order by and group by mysql

tell some big, diff between order by and group by,
like sort columns data=>order by
group it by similar data used for aggregation , order by could be used inside the grouped items ,
please Tell 5 diff
The order by clause is used to order your data set. For example,
select *
from customers
order by customer_id asc
will give you a list of customers in order of customer id from lowest to highest.
The group by clause is used to aggregate your data. For example,
select customer_id, sum(sale_price), max(sale_price)
from customers
group by customer_id
order by customer_id asc
will give you each customer along with their total sales and maximum sale, again ordered by customer id.
In other words, grouping allows you to combine multiple rows from the database into a single output row, based on some criteria, and select functions of those fields not involved in the grouping (minimum, maximum, total, average and so on).
group by groups data by one or more columns, and order by orders the data by one or more columns? i don't really get the question?
using group by is similar to select distinct in the aspect that only unique values for the given values will be returned. furthermore you can use aggregate functions to calculate e.g. the sum for each group.
what do you want to hear? tell me five differences between apples and oranges?