Join on two related tables - sql

I have two tables: One for Invoices and other for their payments:
tbl_Invoice
tbl_payment
The desire output is as below:
PSUM IPRICE
----------- ------------
312.00 1100.00
Where:
PSUM is Sum of Payments.
IPRICE is Sum of Total_price of that client.
Query I tried is:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
group by i.invoice_id
order by i.invoice_id
But it gives wrong output:
PSUM IPRICE
----------- ------------
312.00 400.00
0.00 1000.00

Seems like you want this. This gives the total sum of the amt and the total_price with no grouping. Your version groups by the invoice_id which is the difference:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(distinct i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
See SQL Fiddle with Demo
Another way you could write this is using subqueries:
select
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(i.total_price), 0) IPRICE
from
(
select sum(total_price) total_price, invoice_id, client_id
from tbl_invoice
group by invoice_id, client_id
) i
left join
(
select sum(amt) amt, invoice_id, client_id
from tbl_payment
group by invoice_id, client_id
) p
on i.invoice_id = p.invoice_id
and i.client_id = p.client_id
where i.client_id = 5
See SQL Fiddle with Demo
Both produce the same result:
| PSUM | IPRICE |
-----------------
| 312 | 1100 |

Related

sql join on join

transactions table (1 row --> 1 transaction)
customer_code amount
A0BEFG 100
DEC21A 80
payment table (1 row --> 1 transaction)
customer_id payment_type
1 cash
2 credit_card
customer table (1 row --> 1 customer_code)
customer_code customer_id
A0BEFG 2
DEC21A 1
Expected output:
combined table
customer_code customer_id amount payment_type
AOBEFG 2 100 credit_card
DEC21A 1 80 cash
In words, my idea is to get the payment_type into the transactions table, but because there is no matching variable, I need to first merge payment table and customer table, before connecting them to the transactions table.
Code I've tried:
with
connection as (
select c.customer_code, c.customer_id, p. payment_type
from data.payment p
left join data.customer c on p.customer_id = c.customer_id
),
transactions as (
select t.merchant_code, t.amount
from data.transactions t
)
select
t.merchant_code, c.customer_id, c.amount, p.payment_type
from transactions as t
Code is for PostgreSQL.
SELECT c.customer_code, c.customer_id, t.amount, p.payment_type
FROM customer AS c
INNER JOIN payment AS p ON p.customer_id = c.customer_id
INNER JOIN transactions AS t ON t.customer_code = c.customer_code
Join customer to the other tables like this:
SELECT c.customer_code, c.customer_id, t.amount, p.payment_type
FROM transactions t
INNER JOIN customer c ON t.customer_code = c.customer_code
INNER JOIN payment p ON p.customer_id = c.customer_id
See the demo.
Results:
customer_code
customer_id
amount
payment_type
A0BEFG
2
100
credit_card
DEC21A
1
80
cash

How to show the count of all items in cross joined table in SQL Server

I have a table that has all Items in the inventory, table called CI
CI has 2 columns (ProdID and Price), and it looks like this
ProdID Price
-------------
A8373 700
G8745 900
J7363 300
K7222 800
Y6311 350
I have another table for documents called Docs with columns DocID, CustID and InvoiceID.
DocID, CustID, InvoiceID
------------------------
1 1001 751
2 1001 752
3 1001 753
4 1002 831
5 1002 832
6 1003 901
7 1003 902
Another table for purchases called Purchase with DocID, ProdID, ProdSize.
In the same invoice, ProdID can be repeated as it can be in different sizes
DocID, ProdID, ProdSize
------------------------
1 A8373 41
1 A8373 42
1 A8373 43
1 G8745 35
1 G8745 36
2 A8373 44
2 A8373 45
Now I want to get the quantity of of products for all customer and invoice, but for highest priced products
So it should be like this
CustID, InvoiceID, ProdID, Quantity
-----------------------------------
1001 751 A8373 3
1001 751 G8745 2
1001 751 K7222 0
1001 752 A8373 2
1001 752 G8745 0
1001 752 K7222 0
and to show 0 for the products that do not exist in that invoice
I wrote this query, but it is extremely slow. I wonder if there is an easier fast way to get this results
DECLARE #Features AS TABLE
(
CustID varchar(100),
InvoiceID varchar(100)
INDEX IX3 CLUSTERED(CustID, InvoiceID),
ProdID varchar(100),
Quantity bigint
)
INSERT INTO #Features (CustID, InvoiceID, ProdID, Quantity)
SELECT
R.CustID, R.InvoiceID, T.ProdID, COUNT(*) AS Quantity
FROM
Docs R
CROSS JOIN
(SELECT TOP 1000 * FROM CIs ORDER BY Price DESC) C
INNER JOIN
Purchase T ON T.DocID = R.DocID
GROUP BY
R.CustID, R.InvoiceID, T.ProdID
SELECT TOP 100 *
FROM #Features
ORDER BY CustID, InvoiceID, ProdID
SELECT COUNT(*) FROM #Features
UPDATE F
SET Quantity = Cnt
FROM #Features F
INNER JOIN
(SELECT R.CustID, R.InvoiceID, COUNT(*) Cnt
FROM Purchase T
INNER JOIN Docs R ON T.DocID = R.DocID
GROUP BY R.CustID, R.InvoiceID ) X ON F.CustID = X.CustID
AND F.InvoiceID = X.InvoiceID
SELECT * FROM #Features
here is a way to do this. I filter out the 1000 products first and then perform the join as follows..
Also there isn't a need for update query, all could be obtained in the SQL itself.
Filter early join late
with top_product
as (select prodid,price, rownumber() over(order by price desc) as rnk
from ci
)
,invoice_product
as(select d.docid,d.custid,d.invoiceid,p.prodid
from top_product
join docs d
on 1=1
and rnk<=1000
)
select a.CustID, a.InvoiceID, a.ProdID,count(b.prodid) as qty
from invoice_product a
left join purchase b
on a.DocID=b.docid
and a.ProdID=b.prodid
group by a.CustID, a.InvoiceID, a.ProdID
You can use the DENSE_RANK as follows:
select CustID, InvoiceID, ProdID, sum(qty) as qty
from (select d.CustID, d.InvoiceID, ci.ProdID, p.prodid as qty,
dense_rank() over (order by ci.price desc) as rn
from ci cross join docs d
left join purchase p on d.docid = p.docid and ci.prodid = p.prodid) t
where rn <= 1000
group by CustID, InvoiceID, ProdID
Can you please try following SQL Select statement where I used Common Table Expression SQL CTEs
with topproducts as (
select top 3 ProdID from CI order by Price desc
), sales as (
select
CustID,
InvoiceID,
ProdId,
count(ProdId) as cnt
from (
select
d.CustID,
d.InvoiceID,
p.ProdId
from Docs d
inner join Purchase p
on p.DocID = d.DocID
where p.ProdId in (select ProdId from topproducts)
) t1
group by
CustID,
InvoiceID,
ProdId
)
select
t.*, isnull(ss.cnt,0) as Qty
from (
select
distinct s.CustID, s.InvoiceID, p.ProdId
from sales s, topproducts p
) t
left join sales ss on ss.InvoiceID = t.InvoiceID and ss.ProdId = t.ProdId

Selecting the MIN(date) and the MAX(date) with the MAX(date) Freight Values

I need the MIN(Orderdate) and MAX(Orderdate) with the MAX(Orderdate) Freight values.
I've tried using a CTE and I am struggling to eliminate duplicate rows for the CustomerID
USE Northwind
GO
WITH CTE AS (
SELECT a.customerID,
MAX(b.OrderDate) AS LastOrder,
MIN(b.OrderDate) AS FirstOrder
FROM Orders AS b
INNER JOIN Customers AS a
ON b.CustomerID = a.CustomerID
GROUP BY a.CustomerID
)
SELECT CTE.customerID, CTE.FirstOrder, d.OrderDate as LastOrder, d.Freight
FROM CTE
INNER JOIN Orders as d
On CTE.CustomerID = d.CustomerID
GROUP BY CTE.CustomerID, CTE.FirstOrder, d.Freight, d.OrderDate
HAVING d.OrderDate = MAX(d.OrderDate)
I am trying to get these results which should display 89 records.
CustomerID FirstOrder LastOrder Freight
| ALFKI | 1997-08-25 | 1998-04-09 | 1.21 |
| ANATR | 1996-09-18 | 1998-03-04 | 39.92 |
| ANTON | 1996-11-27 | 1998-01-28 | 58.43 |
| AROUT | 1996-11-15 | 1998-04-10 | 33.80 |
| BERGS | 1996-08-12 | 1998-03-04 | 151.52 |
Just to Keep it simple and in line with the question. The Subquery CTE already has the customerID and the LastOrder(Max Order Date). Joining the LastOrder column in CTE to the Order tables OrderDate will give the expected results.
and d.OrderDate = CTE.LastOrder
Full Query:
WITH CTE AS (
SELECT a.customerID,
MAX(b.OrderDate) AS LastOrder,
MIN(b.OrderDate) AS FirstOrder
FROM Orders AS b
INNER JOIN Customers AS a
ON b.CustomerID = a.CustomerID
GROUP BY a.CustomerID
)
SELECT CTE.customerID, CTE.FirstOrder, d.OrderDate as LastOrder, d.Freight
FROM CTE
INNER JOIN Orders as d
On CTE.CustomerID = d.CustomerID
and d.OrderDate = CTE.LastOrder
Just use conditional aggregation:
SELECT o.customerID,
MAX(o.OrderDate) AS LastOrder,
MIN(o.OrderDate) AS FirstOrder,
MAX(CASE WHEN seqnum = 1 THEN o.freight END) as lastFreight
FROM (SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY o.customerID ORDER BY o.OrderDate DESC) as seqnum
FROM Orders o
) o
GROUP BY o.CustomerID;
Note that you do not appear to need the Customer table. All the information you need is in Orders (I doubt you are using Customer to remove rows.)

Count Customers based on item master

I need you to help me on writing two queries in SQL Server 2008 that shows the following information based on item master:
Brand wise count on customer master plus customer who purchased the brand
Item Wise count of customer master plus customer who purchased the item
Here the link that shows the table information and the query which I tried.
Click here to view the table in SQL Fiddle
SELECT
brandname,
division,
route,
DivisionTotalCustomersCount = MAX(DivisionTotalCustomersCount),
RouteTotalCustomersCount = MAX(RouteTotalCustomersCount),
PurchasedCustomersCount = SUM(PurchasedCustomersCount)
FROM
(SELECT
i.brandname,
c.division,
c.route,
DivisionTotalCustomersCount =
(SELECT COUNT(distinct x.CustomerID)
FROM CustomerMaster x
WHERE x.division = c.division),
RouteTotalCustomersCount =
(SELECT COUNT(distinct x.CustomerID)
FROM CustomerMaster x
WHERE x.Route = c.route),
PurchasedCustomersCount = count(distinct C.CustomerID)
FROM CustomerMaster c
LEFT OUTER JOIN SalesData s on c.CustomerID = s.CustomerID
right outer join ItemMaster i on s.item = i.itemcode
GROUP BY i.brandname, c.division, c.route) A
GROUP BY
brandname, division, route
ORDER BY 1
Result Should as below
Excelsheet
I think you need to go reconsider the report and maybe splitting it out into multiple reports.
It does not make sense to have a route count as well as a divisional count if they are counting things at different levels of aggregation. So have a route count and division count report.
Either way, division and route is going to be null for 100PLUS because there are no customers for that brand which means there is no route or division info available.
--Division Count
SELECT BrandName, Division, COUNT(CustomerMaster.CustomerID) [Customer Count]
FROM ItemMaster LEFT OUTER JOIN
SalesData ON ItemMaster.BrandName = SalesData.Brand LEFT OUTER JOIN
CustomerMaster ON SalesData.CustomerID = CustomerMaster.CustomerID
GROUP BY BrandName, Division
--Route Count
SELECT BrandName, Route, Division, COUNT(CustomerMaster.CustomerID) [Customer Count]
FROM ItemMaster LEFT OUTER JOIN
SalesData ON ItemMaster.BrandName = SalesData.Brand LEFT OUTER JOIN
CustomerMaster ON SalesData.CustomerID = CustomerMaster.CustomerID
GROUP BY BrandName, Route, Division
Using your sqlfiddle data there are 25 sales records & 18 distinct brand/ division/ route/ customer records and there are no sales invloving 100PLUS
select
B.BrandName
, V.Division
, coalesce(Brand_count,0) as Brand_count
, coalesce(Division_count,0) as Division_count
from (select distinct BrandName from ItemMaster) as B
cross join (select distinct Division from CustomerMaster) as V
left join (
select
Brand
, Division
, sum(cust_count) over (partition by Brand) as Brand_count
, sum(cust_count) over (partition by Division) as Division_count
from (
select
S.Brand
, C.Division
, count(distinct S.CustomerID) cust_count
from salesdata as S
inner join CustomerMaster as C
on S.CustomerID = C.CustomerID
inner join ItemMaster as I
on S.item = I.ItemCode
group by
S.Brand
, C.Division
) as S
) as D
on B.BrandName = D.Brand
and V.Division = D.Division
order by
B.BrandName
, V.Division
;
| BRANDNAME | DIVISION | BRAND_COUNT | DIVISION_COUNT |
|-----------|----------|-------------|----------------|
| 100PLUS | Dubai | 0 | 0 |
| 100PLUS | RAK | 0 | 0 |
| KITCO | Dubai | 9 | 11 |
| KITCO | RAK | 9 | 7 |
| Red Bull | Dubai | 9 | 11 |
| Red Bull | RAK | 9 | 7 |
http://sqlfiddle.com/#!3/fecb0/27
All Credit to #kevriley
select
A.BrandName,
B.Division,
B.Route,
B.DivisionTotalCustomers,
B.RouteTotalCustomers,
isnull(C.PurchasedCustomersCount,0) as PurchasedCustomersCount
from
(
select distinct
BrandName, Route, Division
from dbo.ItemMaster
cross join dbo.CustomerMaster
) A
join
(
select distinct
Division,
Route,
DENSE_RANK() over (partition by Division order by c.CustomerID asc) + DENSE_RANK() over (partition by Division order by c.CustomerID desc) - 1 as DivisionTotalCustomers ,
DENSE_RANK() over (partition by ROUTE order by c.CustomerID asc) + DENSE_RANK() over (partition by ROUTE order by c.CustomerID desc) - 1 as RouteTotalCustomers
from CustomerMaster c
left join SalesData s on c.CustomerID = s.CustomerID
) B on B.Division = A.Division and B.Route = A.Route
left join
(
select
s.brand,
c.division,
c.route,
PurchasedCustomersCount = count(distinct C.CustomerID)
FROM CustomerMaster c
JOIN SalesData s on c.CustomerID = s.CustomerID
--join ItemMaster i on s.item = i.itemcode
GROUP by s.brand, c.division, c.route
) C on A.Brandname = C.Brand and C.Division = A.Division and C.Route = A.Route
See the same on SQL Fiddle
Select B.Brandname,B.Division,C AS DivisionTotalCustomerCount,
ISNULL(T.Count,0) AS PURCHASEDCUSTOMERSCOUNT
from
(
Select CM.Division,M.BrandName,COUNT(distinct CM.CustomerID) AS C
from dbo.CustomerMaster CM
CROSS JOIN ItemMaster M
GROUP BY CM.Division,M.BrandName
)B
LEFT JOIN
(Select Division,Brand,COUNT(Distinct C.CustomerID) As Count from CustomerMaster C
JOIN salesdata D
On C.CustomerID=D.CustomerID
where D.Brand='Red Bull'
GROUP BY Division,Brand
)T
ON B.Brandname=T.Brand
and B.Division=T.Division
Order by 1,2

MS Access SQL Query - Joining 3 Tables to receive Total Order Price

I would like to know the total price for a specific order ID. The information is contained in these tables:
Order_line_t
Order_ID Product_ID Quantity
-------- ---------- --------
1006 4 1
1006 5 2
1006 7 2
Uses_t
Product_ID Material_ID Footage
---------- ----------- -------
4 16 20
5 15 13
7 10 16
Raw_Materials_t
Material_ID Unit_Price
----------- ----------
16 05.70
15 16.72
10 15.55
The total cost is computed by
Multiplying SUM ( Order_line_t.Quantity * Uses_t.Footage * Raw_Materials_t.Unit_Price) AS Total
My current query only returns an error:
SELECT Order_line_t.Order_ID, Order_line_t.Product_ID, Uses_t.Product_ID ,Uses_t.Footage ,
SUM ( Order_line_t.Quantity * Uses_t.Footage * Raw_Materials_t.Unit_Price) AS Total
FROM Order_line_t, Uses_t , Raw_Materials_t
WHERE Order_line_t.Order_ID = 1006;
Help appreciated! How exactly do I JOIN these tables? What am i missing?
Firstly you were missing the actual joins between the tables, and secondly you were missing your group by
SELECT Order_line_t.Order_ID,
Order_line_t.Product_ID,
Uses_t.Product_ID ,
Uses_t.Footage ,
SUM ( Order_line_t.Quantity * Uses_t.Footage * Raw_Materials_t.Unit_Price) AS Total
FROM Order_line_t INNER JOIN
Uses_t ON Order_line_t.Product_ID = Uses_t.Product_ID INNER JOIN
Raw_Materials_t ON Uses_t.Material_ID = Raw_Materials_t.Material_ID
WHERE Order_line_t.Order_ID = 1006;
GROUP BY Order_line_t.Order_ID,
Order_line_t.Product_ID,
Uses_t.Product_ID ,
Uses_t.Footage
EDIT
Try this
SELECT Order_line_t.Order_ID,
Order_line_t.Product_ID,
Uses_t.Product_ID,
Uses_t.Footage,
Sum([Order_line_t].[Quantity]*[Uses_t].[Footage]*[Raw_Materials_t].[Unit_Price]) AS Total
FROM (Order_line_t INNER JOIN
Uses_t ON Order_line_t.Product_ID = Uses_t.Product_ID) INNER JOIN
Raw_Materials_t ON Uses_t.Material_ID = Raw_Materials_t.Material_ID
GROUP BY Order_line_t.Order_ID,
Order_line_t.Product_ID,
Uses_t.Product_ID,
Uses_t.Footage;
EDIT
Total by ORDER ID
SELECT Order_line_t.Order_ID,
Sum([Order_line_t].[Quantity]*[Uses_t].[Footage]*[Raw_Materials_t].[Unit_Price]) AS Total
FROM (Order_line_t INNER JOIN
Uses_t ON Order_line_t.Product_ID = Uses_t.Product_ID) INNER JOIN
Raw_Materials_t ON Uses_t.Material_ID = Raw_Materials_t.Material_ID
GROUP BY Order_line_t.Order_ID;
I think you need to compute the cost for each row, then sum the entire order. Something like:
select
Order_ID, sum(RowCost) as OrderCost
from (
select
o.Order_ID, o.Product_ID, o.Quantity,
u.Material_ID, u.Footage,
r.Unit_Price,
(o.Quantity * u.Footage * r.UnitPrice) as RowCost
from
order_line_t o INNER JOIN
uses_t u on o.Product_ID = u.Product_ID INNER JOIN
Raw_materials_t r on u.Material_ID = r.Material_ID
where
o.Order_ID = 1006
) z
group by
Order_ID