SQL aggregate query repeating primary key column - sql

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.

Related

SQL - Join multiple table

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.

PRINT only SUM by year (group by Territory) in SQL

SELECT year(soh.OrderDate) 'year',sum(soh.TotalDue) 'Total',st.[Group] TerritoryGroup
FROM Sales.SalesOrderHeader soh
LEFT OUTER JOIN Sales.SalesTerritory st
ON soh.TerritoryID=st.TerritoryID
GROUP BY year(soh.OrderDate),(soh.TotalDue),[Group]
ORDER BY year(soh.OrderDate),(soh.TotalDue)
This is what I came up with, but the years are scattered instead of ONE year per Territory total.
(I like to print the Total for each year in each Territory)
Is there a concise way to make this select statement?
If you want one row per year, then only include that in the group by:
SELECT year(soh.OrderDate) as year, sum(soh.TotalDue) as Total
FROM Sales.SalesOrderHeader soh LEFT OUTER JOIN
Sales.SalesTerritory st
ON soh.TerritoryID = st.TerritoryID
GROUP BY year(soh.OrderDate)
ORDER BY year(soh.OrderDate);
If you want one row per year and territory group, then include only those two columns:
SELECT year(soh.OrderDate) as year, sum(soh.TotalDue) as Total, st.[Group] as TerritoryGroup
FROM Sales.SalesOrderHeader soh LEFT OUTER JOIN
Sales.SalesTerritory st
ON soh.TerritoryID = st.TerritoryID
GROUP BY year(soh.OrderDate), [Group]
ORDER BY year(soh.OrderDate), Total;
Some notes:
You do not need single quotes around the column aliases. You should use single quotes only for string and date constants.
If you are summarizing just by year, then you cannot have TerritoryGroup in the output.
In neither case would you include soh.TotalDue in the group by. You are summing that column, not aggregating by it.
The order by clause should not contain soh.TotalDue; it should be the aggregated value (Total) instead.
In GROUP BY you say you want one line per combination of year, totaldue and territory group.
Let's say you have these records:
orderdate totaldue territorygroup
2014-01-01 100 1
2014-01-15 200 1
2014-01-21 100 1
2013-03-03 100 1
2014-04-04 100 2
Then you get these result records:
year totaldue territorygroup
2014 100 1
2014 200 1
2013 100 1
2014 100 2
(BTW: sum(soh.TotalDue) = soh.TotalDue, because you group by TotalDue.)
So the solution for you is to say what you want to see in your result records actually. One record per ______. Thus you get your GROUP BY clause and the results you want.

Trying to get Month to date sales value for each date

I have Shipdate and Totaldue column in my salesOrderheader table.
My current query is like this
select
[ShipDate], SUM([TotalDue]) Total
from
Sales.SalesOrderHeader
where
[ShipDate] between '2005-08-1' and '2005-08-31'
group by
[ShipDate]
This returns the result for total sales for each day, I want a result where each date column corresponds to a value which shows month to date sale (i.e. totaldue here). Like if total due for 2005-08-1 is $1000 ,total due for 2005-08-2 is $3000 and total due for 2005-08-3 is $6000 then result should be,
ShipDate MTD Value
-----------------------
2005-08-1 1000
2005-08-2 4000
2005-08-3 11000
And so on till 2008-08-31. I am kind of new to database and can't seem to figure this out. If anybody has idea how do to it, please help me out. Thanks
You could do it like this:
select soh1.ShipDate, SUM(soh2.TotalDue) from
(select distinct ShipDate from sales.SalesOrderHeader
where ShipDate < '2005-09-01' and ShipDate >= '2005-08-01') as soh1
join sales.SalesOrderHeader soh2
on soh2.ShipDate <= soh1.ShipDate and soh2.ShipDate >= '2005-08-01'
group by soh1.ShipDate order by soh1.ShipDate
The join will create the following resultset:
ShipDate MTD Value
2005-08-1 1000
2005-08-2 1000
2005-08-2 4000
2005-08-3 1000
2005-08-3 4000
2005-08-3 11000
and the Sum and Group By joins the dates togheter.
This works and performs reasonably well:
;with soh as (
select ShipDate, sum(TotalDue) as TotalDue
from Sales.SalesOrderHeader
where ShipDate between '20050801' and '20050831'
group by ShipDate
)
select ShipDate, sum(TotalDue) over(order by ShipDate) as Total
from soh

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 get previous values form last transaction using PK and FK

I have this SQL Queries,
SELECT PaymentID, CustomerID, PaymentDate, Amount, Balance, Credit
FROM Payment
WHERE (PaymentDate = '2012-11-03')
I also like to print previous Balance and Credit form last transaction of the customer.
This is my try.
SELECT DISTINCT TOP 1 Balance, Credit, PaymentID
FROM Payment
WHERE CustomerID = '??' AND PaymentID < '??'
ORDER BY PaymentID DESC
As you can see this does nothing as Queries are not liked.
I think I have I have to use T-SQL or UNION but have no idea How to implement it.
This kind of Output I am trying to achieve.
Payment Table
PaymentID int
CustomerID varchar(50)
PaymentDate date
Amount decimal(18, 2)
Balance decimal(18, 2)
Credit decimal(18, 2)
Note:
This is for all the customers not only for single customer, it's like a sale Report.
There are can be more than one payment per customer in a day.
This might get you started
SELECT P1.paymentID, P1.CustomerID, P1.PaymentDate, max(PP.paymentID)
FROM Payment P1
Join Payment PP
on PP.paymentID < P1.paymentID
and PP.CustomerID = P1.CustomerID
and P1.PaymentDate = '2012-11-03'
GroupBy P1.paymentID, P1.CustomerID, P1.PaymentDate
not test but I think this will pull in the other data
select PC.*, PL.PaymentDate, PL.Amount, PL.Balance, PL.Credit
from
(SELECT P1.paymentID, P1.CustomerID, P1.PaymentDate, max(PP.paymentID) as PriorPID
FROM Payment P1
Join Payment PP
on PP.paymentID < P1.paymentID
and PP.CustomerID = P1.CustomerID
and P1.PaymentDate = '2012-11-03'
GroupBy P1.paymentID, P1.CustomerID, P1.PaymentDate) as PC
join Payment PL
on PL.paymentID = PC.PriorPID
and PL.CustomerID = PC.CustomerID