I am trying to have the results from two columns in table1 subtracted from one another and add the total from table2 should the data exist in that table. Not always will there be data in table2 so if there is nothing there I need to use “0”. Here is what I have so far which returns the wrong amount when there IS data in table2.
SELECT
CONVERT(CHAR(10),table1.PostingDate, 120) AS business_date,
table1.Location AS store_number,
(CASE WHEN COUNT(table2.Document) > 0 THEN
SUM(table1.Total - table1.TipAmount + table2.Total)
Else
SUM(table1.Total-table1.TipAmount)
END) AS net_sales_ttl
FROM table1
left join table2
on CONVERT(CHAR(10),table1.PostingDate, 120) = CONVERT(CHAR(10),table2.PostingDate, 120)
WHERE table1.PostingDate between '2012-09-09' and '2012-09-16'
GROUP BY CONVERT(CHAR(10),table1.PostingDate, 120), table1.Location
Here is the results:
business_date store_number net_sales_ttl
2012-09-09 xxx 1699.61
2012-09-10 xxx 923.56
2012-09-11 xxx 1230.93 <--This should be 1399.93
2012-09-12 xxx 874.98
2012-09-13 xxx 1342.21
2012-09-14 xxx 1609.6
2012-09-15 xxx 2324.31
For some reason the query is not doing the math correctly and returning the wrong values. The only day that table2 has a value is 09-11-12 and that amount is only -1.00. It is giving me 1230.93 which is -169 from the correct value. I don’t know where the -169 is coming from when it should be -1.00. Original amount is 1400.93 in table1 and table2 should be subtracted from that which is -1.00 giving a result of 1399.93.
Sample data:
table1 has date, location, and sales
09-09 1111 5.00
09-10 1111 3.00
09-11 1111 7.00
09-12 1111 10.00
table2 has refunds
09-11 1111 -1.00
Return set would look like this:
09-09 1111 5.00
09-10 1111 3.00
09-11 1111 6.00 <--Reflecting the refund from table2
09-12 1111 10.00
try
Also, some sample data would help – the totals alone can’t help
Based on your sample data, try this.