SQL grouping results in a select - sql

My SQL table "offers" contains offers users make for products (product_ID, customer_ID, offer).
In my admin page, I want to list the products for which at least one offer exists and show the total offers existing for it.
For example,
PRODUCT #324 Total offers: 42
PRODUCT #99 Total offers: 1
etc.
My guess would be to combine a
SELECT DISTINCT product_ID FROM offers...
And in a second query, to SELECT COUNT(*) FROM offers WHERE product_ID=...
Is it the most efficient way to achieve this, or is there a way to make it inside a single query?

You can do this in one query which will get the count by grouping by the product_id:
SELECT product_ID, COUNT(*)
FROM offers
GROUP BY product_ID

As bluefeet already answered, you achieve it in single query by using group by.
(group by demo)
Another thing to mention is the order by,
select
product_id as id,
count(*) as totals
from
t
group by product_id
order by totals;
If you want to sort with the totals of hits, or if you want to sort by product_id etc.
sqlfiddle

Related

Average Quantity with subselect

I have following table, where OrderID is unique and ordernumber is not unique:
OrderID|Ordernumber|ProductID|Quantity
1|1234|10|12|
2|1234|55|10|
3|1234|55|22|
4|1029|99|44|
1.I want complete table and using subselect to get average quantity per ordernumber , but as far I know subselect only allows one Column.
And another query where the avg is per Ordernumber and per Prod
OrderID|Ordernumber|ProductID|AVGQuantity
1|1234|10|14,7|
2|1234|55|14,7|
3|1234|55|14,7|
4|1029|99|44|
Outcome should be:
OrderID|Ordernumber|ProductID|AVGQuantity
1|1234|10|11|
2|1234|55|11|
3|1234|55|22|
4|1029|99|44|
Thanks in advance.
This answers the original version of the question.
You can use window functions:
select t.*,
avg(quantity) over (partition by ordernumber) as avg_quantity
from t;

Using SQL to find total amount donated to organizations

I have a SQL table with 2 columns,
organization_id,
amount_donated
I want to return a new table with 2 columns,
organization_id
total_amount_donated
How would I go about finding the total amount donated to each organization? I am thinking I have to use GROUP BY but I haven't been able to find a solution.
You're right, you do want to use GROUP BY. This is because you need to use the SUM aggregate function, and by using GROUP BY organization_id you will sum the amounts corresponding to each organization.
SELECT organization_id, SUM(amount_donated) AS total_amount_donated
FROM your_table
GROUP BY organization_id
This is pretty simple SQL, you should probably get your hands on a tutorial or a book to step you through the basics. :)
You should't to create table, because it will create duplicate data. Instead create a VIEW.
CREATE VIEW vw_total_donation
AS
SELECT organization_id, SUM(amount_donated) tot_donation
FROM table1
GROUP BY organization_id
select organisation_id,sum(amount_donated) as total_amt_donated from your_table
group by organisation_id
You can query like this

Count(), max(),min() fuctions definition with many selects

Lets say we have a view/table hotel(hotel_n,hotel_name, room_n, price). I want to find the cheapest room. I tried group by room_n, but I want the hotels name (hotel_name) to be shown to the board without grouping it.
So as an amateur with sql(oracle 11g) I began with
select hotel_n, room_n, min(price)
from hotel
group by room_n;
but it shows the error: ORA-00979: not a GROUP BY expression. I know I have to type group by room_n, hotel_n, but I want the hotel_n to be seen in the table that I make without grouping by it!
Any ideas? thank you very much!
Aggregate functions are useful to show, well, aggregate information per group of rows. If you want to get a specific row from a group of rows in relation to the other group members (e.g., the cheapest room per room_n), you'd probably need an analytic function, such as rank:
SELECT hotel_n, hotel_name, room_n, price
FROM (SELECT hotel_n, hotel_name, room_n, price
RANK() OVER (PARTITION BY room_n ORDER BY price ASC) rk
FROM hotel) t
WHERE rk = 1

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?

How do I use T-SQL Group By

I know I need to have (although I don't know why) a GROUP BY clause on the end of a SQL query that uses any aggregate functions like count, sum, avg, etc:
SELECT count(userID), userName
FROM users
GROUP BY userName
When else would GROUP BY be useful, and what are the performance ramifications?
To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this:
SELECT WidgetCategory, count(*)
FROM Widgets
GROUP BY WidgetCategory
HAVING count(*) > 5
The "having" clause is something people often forget about, instead opting to retrieve all their data to the client and iterating through it there.
GROUP BY is similar to DISTINCT in that it groups multiple records into one.
This example, borrowed from http://www.devguru.com/technologies/t-sql/7080.asp, lists distinct products in the Products table.
SELECT Product FROM Products GROUP BY Product
Product
-------------
Desktop
Laptop
Mouse
Network Card
Hard Drive
Software
Book
Accessory
The advantage of GROUP BY over DISTINCT, is that it can give you granular control when used with a HAVING clause.
SELECT Product, count(Product) as ProdCnt
FROM Products
GROUP BY Product
HAVING count(Product) > 2
Product ProdCnt
--------------------
Desktop 10
Laptop 5
Mouse 3
Network Card 9
Software 6
Group By forces the entire set to be populated before records are returned (since it is an implicit sort).
For that reason (and many others), never use a Group By in a subquery.
Counting the number of times tags are used might be a google example:
SELECT TagName, Count(*)
AS TimesUsed
FROM Tags
GROUP BY TagName ORDER TimesUsed
If you simply want a distinct value of tags, I would prefer to use the DISTINCT statement.
SELECT DISTINCT TagName
FROM Tags
ORDER BY TagName ASC
GROUP BY also helps when you want to generate a report that will average or sum a bunch of data. You can GROUP By the Department ID and the SUM all the sales revenue or AVG the count of sales for each month.