Select sum from - sql

I am trying to get the sum of all the rows associated with each customer and join on them.
However I am finding that if no rows exist it leaves out the customer completely.
I would prefer if the sum was zero. How would I achieve this.
Here is the SQL statement:
SELECT
Id, DebitSum
FROM
Customers
JOIN
(SELECT
SUM(Amount) DebitSum, CustomerId
FROM
Purchases
WHERE
Completed IS NULL
GROUP BY
CustomerId) p ON p.CustomerId = Id;
Using SQL Server, if it matters.

Just use LEFT JOIN:
SELECT c.Id, COALESCE(p.DebitSum, 0)
FROM Customers c LEFT JOIN
(SELECT SUM(p.Amount) as DebitSum, p.CustomerId
FROM Purchases p
WHERE p.Completed IS NULL
GROUP BY CustomerId
) p
ON p.CustomerId = c.Id;
This would normally be written without the subquery:
SELECT c.Id, COALESCE(SUM(p.Amount), 0) as DebitSum
FROM Customers c LEFT JOIN
Purchases p
ON p.CustomerId = c.Id;
WHERE p.Completed IS NULL
GROUP BY c.Id

You could use LEFT JOIN:
SELECT Id, COALESCE(DebitSum,0) AS DebitSum
FROM Customers
LEFT JOIN (
SELECT SUM(Amount) DebitSum, CustomerId
FROM Purchases
WHERE Completed IS NULL
GROUP BY CustomerId
) p ON p.CustomerId = Id;

Try this:
SELECT Id, DebitSum
FROM Customers
LEFT JOIN (
SELECT SUM(Amount) DebitSum, CustomerId
FROM Purchases
WHERE Completed IS NULL
GROUP BY CustomerId
) p ON p.CustomerId = Id;
Your doing a JOIN which means it has to exist in both tables/data sets. Changing it to LEFT JOIN only requires it to be in the First table and not the one after the LEFT JOIN

You can also use subquery only:
select id, (select coalesce(sum(p.Amount), 0)
from Purchases p
where p.CustomerId = c.id and p.Completed IS NULL
) as DebitSum
from Customers c
group by id;

SELECT SUM(Amount) DebitSum, CustomerId
there is no AS after the information? select sum(amount) as debitsum, customerid

try this
SELECT c.Id, COALESCE(p.DebitSum, 0) as DebitSum
FROM Customers c LEFT JOIN Purchases p
on c.Id = p.CustomerId
where p.completed is null

Related

need help to write a query about this db

I have this DB and I need help with this query
Find the customer ID, first name, last name and the movie Name
of the customer that bought the most ticket in that day
I found the customer who bought the highest number of tickets in that day, now I need to find the movies that he bought tickets for
SELECT c.*, COUNT(*) 'bought'
FROM customer c JOIN ticket t ON c.customerId=t.customerId
GROUP BY c.customerId
HAVING bought=(SELECT MAX(T1.CNT)
FROM (SELECT COUNT(*) AS CNT
FROM customer c JOIN ticket t ON c.customerId=t.customerId
GROUP BY c.customerId) AS T1)
So without building the database and populating it with dummy data I can't test this, but I think I found a solution for you.
SELECT C.CUSTOMERID, C.FIRSTNAME, C.LASTNAME, M.TITLE
FROM CUSTOMER C JOIN TICKET T ON C.CUSTOMERID = T.CUSTOMERID JOIN SHOWS S ON T.SHOWNUMBER = S.SHOWNUMBER JOIN MOVIE M ON M.MOVIEID = S.MOVIEID
WHERE C.CUSTOMERID IN(
SELECT C1.CUSTOMERID FROM(
SELECT CUST.CUSTOMERID, COUNT(*) 'BOUGHT'
FROM CUSTOMER CUST JOIN TICKET TICK ON CUST.CUSTOMERID = TICK.CUSTOMERID
GROUP BY CUST.CUSTOMERID
HAVING BOUGHT = (SELECT MAX(T1.CNT) FROM (SELECT COUNT(*) AS CNT FROM CUSTOMER CUSTO JOIN TICKET TICKE ON CUSTO.CUSTOMERID = TICKE.CUSTOMERID GROUP BY CUSTO.CUSTOMERID)AS T1) AS C1);

SQL Select query for Select 3 different products

Good Evening,
I've been struggling with a select query on my database on which I want to determine the clients that have placed an order of 3 products from at least 3 different product categories.
Then I want to print the CustomerID and the number of the orders.
This is my Database diagram:
Any Answer would be helpful,
Sincerely Thanos.
I haven't tested this, but I believe it should be close to correct:
SELECT h.CustomerID, COUNT(DISTINCT h.SalesOrderID)
FROM SalesOrderHeader h
INNER JOIN SalesOrderDetail d1 ON h.SalesOrderID = d1.SalesOrderID
INNER JOIN SalesOrderDetail d2 ON h.SalesOrderID = d2.SalesOrderID
INNER JOIN SalesOrderDetail d3 ON h.SalesOrderID = d3.SalesOrderID
INNER JOIN Product p1 ON d1.ProductID = p1.ProductID
INNER JOIN Product p2 ON d2.ProductID = p2.ProductID
INNER JOIN Product p3 ON d3.ProductID = p3.ProductID
WHERE p1.ProductCategoryID <> p2.ProductCategoryID
AND p2.ProductCategoryID <> p3.ProductCategoryID
AND p1.ProductCategoryID <> p3.ProductCategoryID
GROUP BY h.CustomerID
select CustomerId, count(*)
from(
select CustomerId
from SalesOrderHeader soh
join SalesOrderDetail sod using (SalesOrderID)
join Product p using (ProductId)
group by CustomerId, SalesOrderId
having count(distinct ProductCategoryID) > 2
) a
group by CustomerId
I think this should get you the result
Select CustomerID,SalesOrderID , count(CategoryID) CatCount
From
SalesOrderHeader Head inner join SalesOrderDetail Det
on Head.SalesOrderID = Det.SalesOrderID
inner join Product Prod
on Prod.ProductID = Det.ProductID
inner join ProductCategory PCat
on Prod.CategoryID = PCat.CategoryID
Group By CustomerID,SalesOrderID
Having count(CategoryID) > 3
like for : "Can't solve this SQL query"
select CustomerID,count(*) as amount_of_order from
SalesOrder join
(
select SalesOrderID,count(distinct ProductCategoryID) CategoryCount
from SalesOrderDetail JOIN Product using (ProductId)
group by 1
) CatCount using (SalesOrderId)
group by 1
having bool_or(CategoryCount>=3) -- At least on CategoryCount>=3

Display 2 columns from one table having max count in column 3 and display computed sum of values from another table

I've a customer table and purchases table,
need to show cname, cid with max(customer_visits) from customer table
and sum of total_purchases by customer in purchases table.
I'm doing something like this
select p.cid, c.cname, sum(p.total_price)
from customers c where exists
(select max(visits_made) from customers having visits_made=max(visits_made)
and cid=p.cid)
inner join purchases p on p.cid=c.cid
group by p.cid,c.cname
and
select p.cid, c.cname, sum(p.total_price)
(select max(visits_made) from customers c where c.cid=p.cid)
from purchases p
inner join customers c on c.cid=p.cid
group by p.cid,c.cname
What's going wrong with these queries?
Found the solution, had to include where clause after inner join :D
I think this is just an aggregation query:
select p.cid, c.cname, sum(p.total_price) as total_price,
max(visits_made) as visits_made
from purchases p inner join
customers c
on c.cid = p.cid
group by p.cid, c.cname;

Finding Sum of all previous sales to all customer and sum of today's sale in sql query

I have following database tables in SQL Server 2008.
customer
------------
id, Name, Address
payment
-------
payment_id, amount, customer_id
Sales
S_id, Date, ItemName, amount, commission, customer_id
I am novice to SQL queries. i want want to to display result
name, previous customer balance i.e (sum(Sale.amount)+Sum(commission))-sum(Payment) for all customers
Something like the below should work:
select c.[Name], saleSum.SaleTotal - paymentSum.PaymentTotal
from customer c join
(
select c.[id], sum(isnull(s.amount,0) + isnull(s.commission, 0)) SaleTotal
from customer c left join sales s on c.id = s.customer_id
group by c.[id]
) as saleSum on c.id = saleSum.id
join
(
select c.id, sum(isnull(p.amount,0)) PaymentTotal
from customer c left join payment p on c.id = p.customer_id
group by c.id
) paymentSum on c.id = paymentSum.id
The equery is
Select Tab1.ID,
Min(Tab1.name),
sum(Tab3.amount) + Sum(Tab3.commission) - sum(Tab2.amount)
From Table1 Tab1
inner join Table2 tab2 on Tab1.id = Tab2.customer_id
inner join Table3 tab3 on Tab1.id = Tab3.customer_id
Group by Tab1.ID
SELECT
customer.name,
(SUM(sales.amount)+SUM(sales.comission)-SUM(payment.amount)) as "customer balance"
FROM
sales
INNER JOIN customer on sales.customer_id = customer.id
INNER JOIN payment on sales.customer_id = payment.customer_id
GROUP BY customer.name

Need to order output based on date - Sub query

I have a simple subquery where I have two tables. First table has the customer id, first name and last name. Second table has the customer id and order date. I want to generate a query that shows the first name, last name and order date.
I have tried the below code and i dont know how the order the output based on date
Select
Customerid,
FirstName,
LastName
From
Customer
Where
CustomerID IN (select
CustomerID
from
orders
where
orderdate is not null);
The output I show is only the customer id, first name and last name. How do I include the order date in my output.
what did u select = what will display for you, include date in your select statement
Select A.Customerid, A.firstname, A.lastname, B.orderdate
From tableA A
Inner join Tableb B on A.customerid = B.customerid
For your modified question(s), try query below
Select A.firstname, A.lastname, B.orderdate
From tableA A
Inner join Tableb B on A.customerid = B.customerid
Order By B.orederdate
;with CustomerProductOrderOrdinal( OrderId, Ordinal )
as
(
select
o.OrderId
, row_number() over ( partition by o.CustomerId, o.ProductId order by o.OrderDate ) Ordinal
from
Orders o
where
o.OrderDate is not null
-- filter for product here if so desired
-- and o.ProductId = <whatever>
)
,FirstCustomerProductOrder( OrderId )
as
(
select
OrderId
from
CustomerProductOrderOrdinal
where
Ordinal = 1
)
select
c.CustomerId
, c.FirstName
, c.LastName
--, p.ProductId
, o.OrderDate
From
Customer c
inner join Orders o
on c.CustomerId = o.CustomerId
inner join FirstCustomerProductOrder fcpo
on o.OrderId = fcpo.OrderId
-- join with product if you want product info
--inner join Product p
-- on o.ProductId = p.ProductId