SQL - Join multiple table - sql

I have four tables Customer, Sales, Invoice, and Receipt.
Customer
ID Name
1 A
Sales
ID Name
1 Ben
Invoice
ID Amt Date CustomerID SalesID
1 12 1/9/2014 1 1
2 10 1/10/2014 1 1
3 20 2/10/2014 1 1
4 30 3/10/2014 1 1
Receipt
ID Amt Date CustomerID SalesID
1 10 4/10/2014 1 1
I wish to join those 4 table as below with sum up the Ammount(s), but I am stuck as to how I can achieve my desired
RESULT
CustomerID SalesID Inv_Amt Rep_Amt Month
1 1 12 0 9
1 1 60 10 10
I've been stuck for days. But, I have no idea how to proceed.

You can get month wise total receipt and invoice amount by grouping and sub query like below :
SELECT Invoice.CustomerID [CustomerID],
Invoice.SalesID [SalesID],
SUM(Invoice.Amt) [Invoice_Amt],
ISNULL((SELECT SUM(Amt)
FROM Receipt
WHERE CustomerID = Invoice.CustomerID
AND SalesID = Invoice.SalesID
AND Month(Date) = Month(Invoice.Date)),0) [Receipt_Amt],
MONTH(Invoice.Date) Month
FROM Invoice
GROUP BY Invoice.CustomerID, Invoice.SalesID, MONTH(Invoice.Date)
SQL Fiddle Demo1
Warning : Here data will come for all months which are in Invoice table. If for any month, there is no any data in invoice table then no result will come for that month even for receipt also.
UPDATE:
To get result from all months of invoice and receipt table, you need to get it using CTE as like below :
;with CTE as
(
SELECT Invoice.CustomerID, Invoice.SalesID, MONTH(Invoice.Date) MonthNo FROM Invoice
UNION
SELECT Receipt.CustomerID, Receipt.SalesID, MONTH(Receipt.Date) MonthNo FROM Receipt
)
SELECT CTE.CustomerID [CustomerID],
CTE.SalesID [SalesID],
ISNULL((SELECT SUM(Amt)
FROM Invoice
WHERE CustomerID = CTE.CustomerID
AND SalesID = CTE.SalesID
AND Month(Date) = CTE.MonthNo),0) [Invoice_Amt],
ISNULL((SELECT SUM(Amt)
FROM Receipt
WHERE CustomerID = CTE.CustomerID
AND SalesID = CTE.SalesID
AND Month(Date) = CTE.MonthNo),0) [Receipt_Amt],
MonthNo
FROM CTE
SQL Fiddle Demo2

Frankly, since you're just selecting customer and sales IDs (as opposed to names), you don't even need to joint all four tables:
SELECT i.CustomerID,
i.SalesID,
SUM(i.Amt) AS InvAmt,
SUM(r.Amt) AS RepAmt,
MONTH(i.`Date`) AS `Month`
FROM Invoice i
JOIN Receipt r ON i.CustomerID = r.CustomerID AND
i.SalesID = r.SalesID AND
MONTH(i.`Date`) = MONTH(r.`Date`)
GROUP BY i.CustomerID, i.SalesID, MONTH(i.`Date`) AS `Month`

Looks like a homework, but ...
SELECT
Customer.ID AS CustomerID,
Sales.ID AS SalesID,
Invoice.Amt AS Inv_Amt,
Receipt.Amt AS Rep_Amt,
MONTH(Invoice.Date) AS Month
FROM
Customer
INNER JOIN Receipt ON Customer.ID = Receipt.CustomerID
INNER JOIN Invoice ON Customer.ID = Invoice.CustomerID
INNER JOIN Sales ON Sales.ID = Receipt.SalesID
I didn't bother checking the result is what you expect, but the query should be something like that. You can play with the join conditions in order to get the result.

Related

On same row: last purchase quantity + date, and total quantity in stock (several stock places) - SQL server

I am trying to get the following result in SQL server:
From the purchase order rows, last purchase quantity + date from all item codes in the order rows table and from the warehouse table amount in stock for the item codes I get from the rows table.
Order rows:
ORDER_DATE ITEM_CODE QTY
2019-03-01 A 5
2019-03-02 A 3
2019-03-05 A 4
2019-03-03 B 3
2019-03-04 B 10
Warehouse:
ITEM_CODE INSTOCK STOCKPLACE
A 10 VV
A 3 LP
A 8 XV
B 5 VV
B 15 LP
Wanted result (Latest order date, latest order qty and total in stock):
ORDER_DATE ITEM_CODE QTY INSTOCK
2019-03-05 A 4 21
2019-03-04 B 10 20
I have tried some queries but only failed. I have a steep learning curve ahead of me :) Thanks in advance for all the help!
Here is one method:
select o.*, wh.*
from (select wh.item_code, sum(wh.instock) as instock
from warehouse wh
group by wh.item_code
) wh outer apply
(select top (1) o.*
from orders o
where o.item_code = wh.item_code
order by o.order_date desc
) o;
You can use row_number() with apply :
select t.*, wh.instock
from (select o.*, row_number () over (partition by item_code order by o.order_date desc) as seq
from Order o
) t cross apply
( select sum(wh.instock) as instock
from warehouse wh
where wh.item_code = t.item_code
) wh
where t.seq = 1;
Your Orders aren't identified with a unique ID, and therefore if multiple Orders were to coincide on the same date, you have no way of telling which is the most recent order on that day.
Anyway, assuming that the database you posted is correct and an Order date + Item Code combines to form a unique key, you could use grouping and some CTE to get the desired output as follows.
;WITH MostRecentOrders (ITEM_CODE, ORDER_DATE)
AS (
SELECT
O.ITEM_CODE
, MAX(O.ORDER_DATE) AS ORDER_DATE
FROM
#Order O
GROUP BY ITEM_CODE
)
SELECT
O.ORDER_DATE
, O.ITEM_CODE
, O.QTY
, SUM(WH.INSTOCK) AS INSTOCK
FROM
#Warehouse WH
INNER JOIN #Order O ON O.ITEM_CODE = WH.ITEM_CODE
INNER JOIN MostRecentOrders MRO ON MRO.ITEM_CODE = O.ITEM_CODE
AND MRO.ORDER_DATE = O.ORDER_DATE
GROUP BY
O.ORDER_DATE
, O.ITEM_CODE
, O.QTY
ORDER BY O.ITEM_CODE

SQL aggregate query repeating primary key column

I am querying two database tables, Invoice and Payments. I want to get the sum of all payments for a particular invoice, however the results 'repeat' the invoice numbers instead of aggregating the values.
The tables are
Invoices
invoiceID
dueDate
invoiceAmount
Payments
paymentID
invoiceID
fine
amount
This is my query :
SELECT
Invoices.invoiceID, invoiceAmount,
COALESCE((SUM (fine + amount)), 0) AS 'Total'
FROM
Payments, Invoices
WHERE
Payments.invoiceID = Invoices.invoiceID
GROUP BY
Invoices.invoiceID, dueDate, datePaid, invoiceAmount
ORDER BY
Invoices.invoiceID
The results of this are something like
invoiceID invoiceAmount Total
---------------------------------
2 270000 170000
2 270000 100000
67 400000 150000
67 400000 250000
I expect the output to be
invoiceID invoiceAmount Total
----------------------------------
2 270000 270000
67 400000 400000
use join and remove dueDate, datePaid from group by
SELECT
Invoices.invoiceID, invoiceAmount,
COALESCE((SUM (fine + amount)), 0) AS 'Total'
FROM
Payments join Invoices
on
Payments.invoiceID = Invoices.invoiceID
GROUP BY
Invoices.invoiceID,invoiceAmount
ORDER BY
Invoices.invoiceID
I suspect that you really want a left join to capture invoices that have no payments:
SELECT i.invoiceID, i.invoiceAmount,
SUM(COALESCE(fine, 0) + COALESCE(amount, 0)) as Total
FROM Invoices i LEFT JOIN
Payments p
ON p.invoiceID = i.invoiceID
GROUP BY i.invoiceID, i.invoiceAmount
ORDER BY i.invoiceID;
Note that COALESCE() is used on each column. If one of the values is NULL, then this probably does what you intend.

How to do a group by without having to pass all the columns from the select?

I have the following select, whose goal is to select all customers who had no sales since the day X, and also bringing the date of the last sale and the number of the sale:
select s.customerId, s.saleId, max (s.date) from sales s
group by s.customerId, s.saleId
having max(s.date) <= '05-16-2013'
This way it brings me the following:
19 | 300 | 26/09/2005
19 | 356 | 29/09/2005
27 | 842 | 10/05/2012
In another words, the first 2 lines are from the same customer (id 19), I wish to get only one record for each client, which would be the record with the max date, in the case, the second record from this list.
By that logic, I should take off s.saleId from the "group by" clause, but if I do, of course, I get the error:
Invalid expression in the select list (not contained in either an
aggregate function or the GROUP BY clause)
I'm using Firebird 1.5
How can I do this?
GROUP BY summarizes data by aggregating a group of rows, returning one row per group. You're using the aggregate function max(), which will return the maximum value from one column for a group of rows.
Let's look at some data. I renamed the column you called "date".
create table sales (
customerId integer not null,
saleId integer not null,
saledate date not null
);
insert into sales values
(1, 10, '2013-05-13'),
(1, 11, '2013-05-14'),
(1, 12, '2013-05-14'),
(1, 13, '2013-05-17'),
(2, 20, '2013-05-11'),
(2, 21, '2013-05-16'),
(2, 31, '2013-05-17'),
(2, 32, '2013-03-01'),
(3, 33, '2013-05-14'),
(3, 35, '2013-05-14');
You said
In another words, the first 2 lines are from the same customer(id 19), i wish he'd get only one record for each client, which would be the record with the max date, in the case, the second record from this list.
select s.customerId, max (s.saledate)
from sales s
where s.saledate <= '2013-05-16'
group by s.customerId
order by customerId;
customerId max
--
1 2013-05-14
2 2013-05-16
3 2013-05-14
What does that table mean? It means that the latest date on or before May 16 on which customer "1" bought something was May 14; the latest date on or before May 16 on which customer "2" bought something was May 16. If you use this derived table in joins, it will return predictable results with consistent meaning.
Now let's look at a slightly different query. MySQL permits this syntax, and returns the result set below.
select s.customerId, s.saleId, max(s.saledate) max_sale
from sales s
where s.saledate <= '2013-05-16'
group by s.customerId
order by customerId;
customerId saleId max_sale
--
1 10 2013-05-14
2 20 2013-05-16
3 33 2013-05-14
The sale with ID "10" didn't happen on May 14; it happened on May 13. This query has produced a falsehood. Joining this derived table with the table of sales transactions will compound the error.
That's why Firebird correctly raises an error. The solution is to drop saleId from the SELECT clause.
Now, having said all that, you can find the customers who have had no sales since May 16 like this.
select distinct customerId from sales
where customerID not in
(select customerId
from sales
where saledate >= '2013-05-16')
And you can get the right customerId and the "right" saleId like this. (I say "right" saleId, because there could be more than one on the day in question. I just chose the max.)
select sales.customerId, sales.saledate, max(saleId)
from sales
inner join (select customerId, max(saledate) max_date
from sales
where saledate < '2013-05-16'
group by customerId) max_dates
on sales.customerId = max_dates.customerId
and sales.saledate = max_dates.max_date
inner join (select distinct customerId
from sales
where customerID not in
(select customerId
from sales
where saledate >= '2013-05-16')) no_sales
on sales.customerId = no_sales.customerId
group by sales.customerId, sales.saledate
Personally, I find common table expressions make it easier for me to read SQL statements like that without getting lost in the SELECTs.
with no_sales as (
select distinct customerId
from sales
where customerID not in
(select customerId
from sales
where saledate >= '2013-05-16')
),
max_dates as (
select customerId, max(saledate) max_date
from sales
where saledate < '2013-05-16'
group by customerId
)
select sales.customerId, sales.saledate, max(saleId)
from sales
inner join max_dates
on sales.customerId = max_dates.customerId
and sales.saledate = max_dates.max_date
inner join no_sales
on sales.customerId = no_sales.customerId
group by sales.customerId, sales.saledate
then you can use following query ..
EDIT changes made after comment by likeitlikeit for only one row per CustomerID even when we will have one case where we have multiple saleID for customer with certain condition -
select x.customerID, max(x.saleID), max(x.x_date) from (
select s.customerId, s.saleId, max (s.date) x_date from sales s
group by s.customerId, s.saleId
having max(s.date) <= '05-16-2013'
and max(s.date) = ( select max(s1.date)
from sales s1
where s1.customeId = s.customerId))x
group by x.customerID
You can Try Maxing the s.saleId (Max(s.saleId)) and removing it from the Group By clause
A subquery should do the job, I can't test it right now but it seems ok:
SELECT s.customerId, s.saleId, subq.maxdate
FROM sales AS s
INNER JOIN (SELECT customerId, MAX(date) AS maxdate
FROM sales
GROUP BY customerId, saleId
HAVING MAX(s.date) <= '05-16-2013'
) AS subq
ON s.customerId = subq.customerId AND s.date = subq.maxdate

How to identify to correct row

I have two tables, namely Price List (Table A) and Order Record (Table B)
Table A
SKU Offer Date Amt
AAA 20120115 22
AAA 20120223 24
AAA 20120331 25
AAA 20120520 28
Table B
Customer SKU Order Date
A001 AAA 20120201
B001 AAA 20120410
C001 AAA 20120531
I have to retrieve the correct pricing for each customer based on the order date. The expected output should be like this:-
Customer SKU Order Date Amt
A001 AAA 20120201 22
B001 AAA 20120410 25
C001 AAA 20120531 28
Thanks.
A left join (or NOT EXISTS subquery) can be used to ensure that the join between the two tables uses the "most recent" row from the prices table that is dated on or before the order date. I assume that's the relationship between the tables that you want to achieve:
Setup:
create table Prices (
SKU char(3) not null,
OfferDate date not null,
Amt int not null
)
go
insert into Prices (SKU, OfferDate, Amt) values
('AAA','20120115', 22),
('AAA','20120223', 24),
('AAA','20120331', 25),
('AAA','20120520', 28)
go
create table Orders (
Customer char(4) not null,
SKU char(3) not null,
OrderDate date not null
)
go
insert into Orders (Customer, SKU, OrderDate) values
('A001','AAA','20120201'),
('B001','AAA','20120410'),
('C001','AAA','20120531')
go
Query:
select
o.*, /* TODO - Explicit columns */
p.Amt
from
Orders o
inner join
Prices p
on
o.SKU = p.SKU and
o.OrderDate >= p.OfferDate
left join
Prices p_later
on
o.SKU = p_later.SKU and
o.OrderDate >= p_later.OfferDate and
p_later.OfferDate > p.OfferDate
where
p_later.SKU is null
Next time, do put up what u have tried....
anyways, here is your answer! try...
Select X.Customer , X.SKU , X.OrderDate , Y.Amt from B as X INNER JOIN A as Y ON X.Order Date= Y. Offer Date
good luck...
SELECT o.Customer, o.SKU, o.[Order Date],
(SELECT TOP 1 l.Amt
FROM PriceList l
WHERE l.[Offer Date] <= o.[Order Date] AND o.SKU = l.SKU
ORDER BY l.[Offer Date] DESC) AS Amount
FROM
Orders o
Some things may differ based on database support

SQL: Need help with query construction

I am relatively new with sql and I need some help with some basic query construction.
Problem: To retrieve the number of orders and the customer id from a table based on a set of parameters.
I want to write a query to figure out the number of orders under each customer (Column: Customerid) along with the CustomerID where the number of orders should be greater or equal to 10 and the status of the order should be Active. Moreover, I also want to know the first transaction date of an order belonging to each customerid.
Table Description:
product_orders
Orderid CustomerId Transaction_date Status
------- ---------- ---------------- -------
1 23 2-2-10 Active
2 22 2-3-10 Active
3 23 2-3-10 Deleted
4 23 2-3-10 Active
Query that I have written:
select count(*), customerid
from product_orders
where status = 'Active'
GROUP BY customerid
ORDER BY customerid;
The above statement gives me
the sum of all order under a customer
id but does not fulfil the condition
of atleast 10 orders.
I donot know how
to display the first transaction date
along with the order under a
customerid (status: could be active
or delelted doesn't matter)
Ideal solutions should look like:
Total Orders CustomerID Transaction Date (the first transaction date)
------------ ---------- ----------------
11 23 1-2-10
Thanks in advance. I hope you guys would be kind enough to stop by and help me out.
Cheers,
Leonidas
SELECT
COUNT(*) AS [Total Orders],
CustomerID,
MIN(Transaction_date) AS [Transaction Date]
FROM product_orders
WHERE product_orders.Status = 'Active'
GROUP BY
CustomerId
HAVING COUNT(*) >= 10
HAVING will allow you to filter aggregates like COUNT() & MIN() will show the first date.
select
count(*),
customerid,
MIN(order_date)
from product_orders
where status = 'Active'
GROUP BY customerid
HAVING COUNT(*) >= 10
ORDER BY customerid
If you want the earliest date irrespective of status you can sub-query for it
select
count(*),
customerid,
(SELECT min(order_date) FROM product_orders WHERE product_orders.customerid = p.customerid) AS FirstDate
from product_orders P
where status = 'Active'
GROUP BY customerid
HAVING COUNT(*) >= 10
ORDER BY customerid
This query should give you the total active orders for each customer that has 10 or more active orders. It will also display the first active order date.
Select Count(OrderId) as TotalOrders,
CustomerId,
Min(Transaction_Date) as FirstActiveOrder
From Product_Orders
Where [Status] = 'Active'
Group By CustomerId
Having Count(OrderId)>10
select count(*), customerid, MIN(Transaction_date) from product_orders
where status = 'Active'
GROUP BY customerid having count(*) >= 10
ORDER BY customerid