How to write Group by in Inner Join - sql

Here I Have Two tables:
Orders
OrderId OrderName
1 Apple
2 Mango
Cust
Id Name OrderId Price
1 John 1 50
2 John 1 100
3 Mic 1 10
4 Mic 2 10
Sql Join Query:
SELECT Orders.CustName,Items.IteamName,Orders.Price
FROM Orders JOIN Items ON Items.Id = Orders.Id
Group By
SELECT Orders.CustName, SUM(Price) FROM Orders GROUP BY Orders.CustName
How can I Write Group by in Join?

You can do like this:
Select Orders.CustName, Items.IteamName, SUM(Orders.Price)
FROM
Orders JOIN Items ON Items.Id=Orders.Id
GROUP BY
Orders.CustName, Items.IteamName
The fields that you doesn't aggregate you put at the GROUP BYclause.

Related

SQL get table1 names with a count of table2 and table3

I have three tables, table1 is connected to table2 and table3, but table2 and table3 are not connected. I need an output count of table2 and table3 for each table1 row. I have to use joins and a group by table1.name
SELECT Tb_Product.Name, count(TB_Offers.Prod_ID) 'Number of Offers', count(Tb_Requests.Prod_ID) 'Number of Requests'
FROM Tb_Product LEFT OUTER JOIN
Tb_Requests ON Tb_Product.Prod_ID = Tb_Requests.Prod_ID LEFT OUTER JOIN
TB_Offers ON Tb_Product.Prod_ID = TB_Offers.Prod_ID
GROUP BY Tb_Product.Name
I need to combine these queries:
SELECT Tb_Product.[Name], count(TB_Offers.Prod_ID) 'Number of Offers'
FROM Tb_Product LEFT OUTER JOIN
TB_Offers ON Tb_Product.Prod_ID = TB_Offers.Prod_ID
GROUP BY Tb_Product.[Name]
SELECT Tb_Product.[Name], count(Tb_Requests.Prod_ID) 'Number of Requests'
FROM Tb_Product LEFT OUTER JOIN
Tb_Requests ON Tb_Product.Prod_ID = Tb_Requests.Prod_ID
GROUP BY Tb_Product.[Name]
Results:
Name Number of Offers
Airplane 6
Auto 5
Bike 3
Camera 0
Computer 12
Milk 4
Oil 4
Orange 6
Telephone 0
Truck 6
TV 4
Name Number of Requests
Airplane 1
Auto 5
Bike 0
Camera 2
Computer 6
Milk 4
Oil 5
Orange 6
Telephone 0
Truck 1
TV 5
My results for offers and requests are the same value. I am not sure what I am doing wrong with the joins. Do I need to somehow join product to request and separately join product to offers? This needs to be done in one query.
This is for a class. Explanation would also be appreciated.
The simplest way to do this is to count the distinct values of each column:
SELECT
Tb_Product.Name,
count(distinct TB_Offers.Prod_ID) 'Number of Offers',
count(distinct Tb_Requests.Prod_ID) 'Number of Requests'
FROM
Tb_Product
LEFT OUTER JOIN
Tb_Requests ON Tb_Product.Prod_ID = Tb_Requests.Prod_ID
LEFT OUTER JOIN
TB_Offers ON Tb_Product.Prod_ID = TB_Offers.Prod_ID
GROUP BY
Tb_Product.Name
This is necessary because of the way joins work consecutively to produce a rowset that is a combination of all the input relations. COUNT() normally performs a count of non-null values in a column.
You can also do something like this, which aggregates the counts from the child tables independently and then joins them to the base table:
SELECT
p.Name,
o.cnt as Offer_Count,
r.cnt as Request_Count
FROM
TB_Product p
LEFT OUTER JOIN
(SELECT Prod_ID, COUNT(1) cnt FROM TB_Offers GROUP BY Prod_ID) o
LEFT OUTER JOIN
(SELECT Prod_ID, COUNT(1) cnt FROM TB_Requests GROUP BY Prod_ID) r
More explanation...
Let's say you have two products:
Prod_ID
Name
1
Widget
2
Gizmo
And two offers, one for each product:
Offer_ID
Prod_ID
100
1
200
2
And two requests for each product:
Request_ID
Prod_ID
1001
1
1002
1
2001
2
2002
2
Now you join Product relation to Offer relation on Prod_ID, you get a result like this:
Prod_ID
Name
Offer_ID
Prod_ID
1
Widget
100
1
2
Gizmo
200
2
Now when you join that relation to Requests on Prod_ID, you get something like this:
Prod_ID
Name
Offer_ID
Prod_ID
Request_ID
Prod_ID
1
Widget
100
1
1001
1
1
Widget
100
1
1002
1
2
Gizmo
200
2
2001
2
2
Gizmo
200
2
2002
2
Now when you count any of these columns you get 4 because each column has 4 values.

SQL get SUM, COUNT, max, min and names of invoice

I have the following tables:
invoice
id
customerId
date
1
3
2020-10-10
2
NULL
2020-09-10
3
1
2020-10-15
product
id
name
price
1
car
10
2
pen
5
3
laptop
6
4
table
2
customer
id
name
1
a
2
b
3
c
4
d
invoceProduct
id
invoiceid
productid
1
1
1
3
1
2
4
1
4
5
2
2
6
2
3
I need to get the following for each invoice:
invoiceID, date, customerName, Total, Quantity(count of items), max product name and price, min product name and price in each invoice.
I wrote query and get most of values but I cannot get the name of products.
This is my sql query
WITH cte_Products(InvoiceId, date, CustomerName, ProductName, price) AS
(
select
i.id as InvoiceId,
i.date as date,
CASE
when c.name IS NULL THEN 'NoName'
Else c.name
End AS CustomerName,
p.name as ProductName,
p.price as price
from invoceProduct ip
join product p on p.id = ip.productID
join invoice i on i.id = ip.invoiceId
left join customer c on i.customerId = c.id
)
select
cte.InvoiceId,
cte.date,
cte.CustomerName,
SUM(cte.price) as Total,
count(*) AS ItemsQuantity,
MAX(cte.price) AS MostExpensiveItem,
MIN(cte.price) AS CheapestItem
from
cte_Products cte
group by cte.InvoiceId, cte.date, cte.CustomerName;
I got this result
InvoiceId
date
CustomerName
Total
ItemsQuantity
MostExpensiveItem
CheapestItem
1
2020-10-10
c
17
3
10
2
2
2020-09-10
NoName
11
2
6
5
I need to add the product name with product price under MostExpensiveItem and CheapestItem.

Get ID and name of each customer and the total sum (sum of quantity of products purchased)

I'm struggling with this JOIN + SUM query
What I have are these following tables (Client, orders, product)
client_id
name
1
Frank
2
Emile
3
Rose
4
Laura
5
Samuel
order_number
client_id
product_id
units_sold
1
4
1
11
2
3
2
8
3
5
3
18
4
4
4
19
5
3
5
12
product_id
description
price
1
Rice
26.10
2
Coffee
12.50
4
Sugar
13
5
Beans
5.40
3
Milk
30.00
What I'm trying to do is generate a query that shows the ID and name of each customer and the total sum (sum of quantity of products purchased).
So far, my logic without breaking it is this:
Select
c.client_id, c.first_name
from client c
INNER JOIN orders o on o.client_id = c.client_id
I want to add the SUM part to it but whenever I try it, the new query line doesn't work
If you just want the sum of quantity of products:
SELECT c.client_id, c.first_name, SUM(o.units_sold)
FROM
client c
INNER JOIN orders o ON o.client_id = c.client_id
GROUP BY c.client_id, c.first_name;
But if you also want to see the price:
SELECT c.client_id, c.first_name, SUM(o.units_sold),
SUM(o.units_sold*p.price)
FROM
client c
INNER JOIN orders o ON o.client_id = c.client_id
INNER JOIN products p ON o.product_id = p.product_id
GROUP BY c.client_id, c.first_name;

SQL filter unique and return total

I have two following tables:
products_table
id name
1 productA
2 productB
3 productC
inventory_table
id product_id amount
1 1 200
2 1 300
3 2 100
4 3 200
5 2 500
And the result I would like to get is
name total
productA 500
productB 600
productC 200
How could this be achieved using sql query?
Seems easy, first subSELECT query makes sums, parent one joins the names.
SELECT pt.name, n.total
FROM
(SELECT SUM(it.amount) as total, it.product_id
FROM inventory_table it
GROUP BY it.productID) n JOIN
products_table pt ON pt.id = n.product_id
I would try joining the two tables and use aggregation as
SELECT
p.name,
SUM(i.amount)
FROM product_table as p
LEFT JOIN inventory_table as i
ON p.id = i.product_id
GROUP by p.name
This is a simple inner join between the two tables, grouping by each Product and summing all its values.
select p.[name], Sum(i.amount) Amount
from product_table p join inventory_table i on i.product_id=p.id
group by p.[name]

SQL Construction Error

TABLE : ITEMS
---------------------------------------
Item_ID Description
---------------------------------------
1 Vivel Satin Soap
2 Flake
3 Maggie
4 Mango Juice
---------------------------------------
TABLE : SALES
------------------------------------------------
Sale_ID Sale_Date Item_ID Quantity
------------------------------------------------
1 15-Feb-14 1 2
2 16-Feb-14 1 1
3 16-Feb-14 2 1
4 17-Feb-14 3 1
5 18-Feb-14 1 1
6 18-Feb-14 2 2
------------------------------------------------
I'm having trouble in constructing SQL query as the way i wanted.... Here, i have two
tables in the database as shown above. The "ITEMS" table is for Items' Description Look-up
and "SALES" table for Items' Sale Record Look-up. Now, my requirement is, i want to select a records
from both the tables to generate report (as shown in the following). Report should contain
Items Description and its corresponding Sum of Quantity.
REPORT
------------------------------------------------------
Item_ID Description Total_Quantity
------------------------------------------------------
1 Vivel Satin Soap 4
2 Flake 3
3 Maggie 1
4 Mango Juice (SHOULD BE NULL HERE)
------------------------------------------------------
I tried following SQL query and some more to generate the report but had a logical error....
so, help me to construct better!
1) SELECT I.Item_ID, I.Description, Sum(S.Quantity)
FROM ITEMS I
INNER JOIN SALES S ON I.Item_ID = S.Item_ID
ORDER BY I.Item_ID;
2) Select I.Item_ID, I.Description, Sum(S.Quantity)
From ITEMS I, SALES S
Where S.Item_ID IN (Select Item_ID from ITEMS)
Order by I.Item_ID;
3) etc..........
try this,
SELECT I.Description, Sum(S.Quantity)
FROM ITEMS I
LEFT JOIN SALES S ON I.Item_ID = S.Item_ID
GROUP BY I.Description
Instead of Inner just try with Left Join...
And you need to use Group by Clause
SELECT I.Item_ID, I.Description, Sum(S.Quantity) -- It will return Null for Mango Juice
FROM ITEMS I
LEFT JOIN SALES S ON I.Item_ID = S.Item_ID
Group By I.Item_ID, I.Description
ORDER BY I.Item_ID;
OR:
SELECT I.Item_ID, I.Description, CASE WHEN Sum(S.Quantity) IS NULL THEN 0 ELSE Sum(S.Quantity) END Quantity -- It will return 0 for Mango Juice
FROM ITEMS I
LEFT JOIN SALES S ON I.Item_ID = S.Item_ID
Group By I.Item_ID, I.Description
ORDER BY I.Item_ID;