Calculating payment breakages - sql-server-2008

I'm currently working on a report to highlight payment breakages, this is based on a customer paying in June, but then failing to pay in July.
I've currently got it set up to do an except query, to check one month and compare it to the next. Similar to below(syntax my not be correct as I have had to edit certain data).
DECLARE #StartDatePaid AS DATETIME
DECLARE #EndDatePaid AS DATETIME
DECLARE #StartDateMissed AS DATETIME
DECLARE #EndDateMissed AS DATETIME
SET #StartDatePaid = '01-Oct-2013'
SET #EndDatePaid = '31-Oct-2013'
SET #StartDateMissed = '01-Nov-2013'
SET #EndDateMissed = '05-Dec-2013'
SELECT d.StoreNo
, d.CustNo
FROM (
--Paid Range
SELECT c.CustNo, m.StoreNo
FROM dbo.tblCont AS c INNER JOIN
dbo.tblContDep AS cd ON c.ContractNo = cd.ContractNo INNER JOIN
dbo.tblCust AS m ON c.CustNo = m.CustNo INNER JOIN
dbo.tblTrans AS mx ON m.CustNo = mx.CustNo AND cd.AgendaCode = mx.AgendaCode INNER JOIN
dbo.tblCalender AS cl ON mx.DateEvent = cl.Date
WHERE (cd.Payment > 0) AND (m.Closed <> 'Y') AND (cd.AgendaCode <> 'OPCLIPMT')
AND mx.DateEvent BETWEEN #StartDatePaid AND #EndDatePaid
GROUP BY c.CustNo, m.StoreNo, mx.DateEvent
EXCEPT
--Missed Range
SELECT c.CustNo, m.StoreNo
FROM dbo.tblCont AS c INNER JOIN
dbo.tblContDep AS cd ON c.ContractNo = cd.ContractNo INNER JOIN
dbo.tblCust AS m ON c.CustNo = m.CustNo INNER JOIN
dbo.tblTrans AS mx ON m.CustNo = mx.CustNo AND cd.AgendaCode = mx.AgendaCode INNER JOIN
dtLookups.dbo.tblCalender AS cl ON mx.DateEvent = cl.Date
WHERE (cd.Payment > 0) AND (m.Closed <> 'Y') AND (cd.AgendaCode <> 'OPCLIPMT') AND (mx.DateEvent BETWEEN #StartDateMissed AND #EndDateMissed )
GROUP BY c.CustNo, m.StoreNo, mx.DateEvent
) AS d
WHERE d.StoreNo IN (72, 114, 121, 139, 185, 241, 266)
GROUP BY
d.StoreNo, d.CustNo
I will be switching it over to be based on calendar months instead of date ranges, my question is how am I best generating several months of breakages at once. To get a month on Month comparison at once, as it is I can only get it to create one months breakages based on supplied data.
Example of desired output
Month| breakges
June | 201
July | 189
Aug | 250
Open to suggestions on best practice also or ways to improve.

I admit I don't understand your query. Assuming your breakage is the first occurrence of missing payment, not the subsequent ones. You can produce the desired output like this:
-- prepare your source data
with cte1 as
(
select
user_id,
date, -- representing month by the first day
missed -- bool flag if payment was missed in that month
from ...
)
-- add a sequence number to the source data ordered by date
with cte2 as
(
select *,
row_number() over(partition by user_id order by date) rn
from cte1
)
-- select those records where payment was missed but the previous was ok
,cte3 as
(
select user_id, date from cte2 a
where a.missed = 1
and exists (
select * from cte2 b
where b.missed = 0
and b.uid = a.uid
and b.rn = a.rn -1
)
)
select date, count(*) as breakage from cte3 group by date

Related

SQL query total vs a single value

I've been working on a query with a peer and it has been turning back some unusual numbers. The query is a productivity report. I'm trying to total the all of the billable units for a specific end user, compare that total to single expected value, and then calculate the difference between those 2 numbers within a 1 week period of time. Here is what we have come up with so far:
SELECT
Employees.emp_id,
Employees.last_name+', '+Employees.first_name as staff_name,
SUM(VisitQuery.billed_value)/60 AS billed_value,
SUM(StandardQuery.num8) as expected_value
FROM
Employees
INNER JOIN
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= #param1 AND
ClientVisit.rev_timeout <= #param2
) VisitQuery
ON VisitQuery.emp_id = Employees.emp_id
INNER JOIN
(
SELECT DISTINCT
CaseloadQuery.emp_id,
ClientsExt.num8
FROM
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= #param1 AND
ClientVisit.rev_timeout <= #param2
) CaseloadQuery
INNER JOIN ClientsExt
ON CaseloadQuery.client_id = ClientsExt.client_id
) StandardQuery
ON Employees.emp_id = StandardQuery.emp_id
GROUP BY
Employees.emp_id,
Employees.last_name+', '+Employees.first_name`enter code here`
The return comes out looking like this:
emp_id staff_name billed_value expected_value
X X 74 231
XX XX 108 279
XXX XXX 19 72
Does anyone have any thoughts? The expected value should really not be any higher that 40 hours for the week.
In the table ClientVisit, can the same employee (emp_id) has multiple rows that lead to multiple values of client_id? If the answer is yes, then I think you should also do a GROUP BY on client_id
Below I tried rewriting your query (pay attention to the lines marked with "add" and "delete").
Disclaimer: I don't have your actual DB tables to test my query, so it may have syntax and semantic bugs
SELECT
Employees.emp_id,
StandardQuery.client_id, -- add
Employees.last_name+', '+Employees.first_name as staff_name,
SUM(VisitQuery.billed_value)/60 AS billed_value,
SUM(StandardQuery.num8) as expected_value
FROM
Employees
INNER JOIN
(
SELECT
ClientVisit.duration AS billed_value,
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= #param1 AND
ClientVisit.rev_timeout <= #param2
) VisitQuery
ON VisitQuery.emp_id = Employees.emp_id
INNER JOIN
(
SELECT DISTINCT
CaseloadQuery.emp_id,
ClientsExt.num8,
ClientsExt.client_id -- add
FROM
(
SELECT
-- ClientVisit.duration AS billed_value, -- delete
ClientVisit.emp_id,
ClientVisit.client_id
FROM
ClientVisit
WHERE
ClientVisit.non_billable = 0 AND
ClientVisit.rev_timeout >= #param1 AND
ClientVisit.rev_timeout <= #param2
)CaseloadQuery
INNER JOIN ClientsExt
ON CaseloadQuery.client_id = ClientsExt.client_id
)StandardQuery
ON Employees.emp_id = StandardQuery.emp_id
GROUP BY
Employees.emp_id,
-- Employees.last_name+', '+Employees.first_name -- delete
StandardQuery.client_id -- add

How can I increase the number of years in SQL and in SSRS report?

I have a forecast algorithm
WITH CTE_AllIDs AS
(
SELECT TOP 22 ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM sys.columns
)
SELECT
c.ID
,OrderMonth = CASE WHEN r.ID IS NOT NULL
THEN r.OrderMonth
-- elaborate function to get the short month name and year
ELSE ordermonth + 1
END
,OrderQuantity
,Trend
,Forecast = CASE WHEN Trend IS NOT NULL AND c.ID <> (SELECT MAX(ID) FROM #Temp_Regression)
THEN NULL
-- For the last actual value (September in this example), we want forecast to have the same
-- value as the trendline (instead of NULL). This prevents a gap in the line charts in SSRS.
WHEN Trend IS NOT NULL AND c.ID = (SELECT MAX(ID) FROM #Temp_Regression)
THEN Trend
-- If trend is not found, it means we can calculate a forecast.
-- However, we also need to check if the month for which we calculate the forecast comes after
-- the actual values. Suppose we don't have values for January, then we don't want to calculate
-- a forecast for January as well. Only for the last 3 months of the year in this example.
WHEN Trend IS NULL AND c.ID > (SELECT MAX(ID) FROM #Temp_Regression)
THEN (#slope * (c.ID % 100)) + #intercept
ELSE NULL
END
FROM CTE_AllIDs c
LEFT JOIN #Temp_Regression r ON c.ID = r.ID;
The results
How can I do this in the values of the OrderMoth columns increase by one the? 2023, 2024, etc.
Thanks.
Your Else in your Case Statement will always contain Null. Try this.
ELSE (Select Max(OrderMonth) From #Temp_Regression) + ((C.ID) - (Select Max(ID) From #Temp_Regression))

Calculate Date by number of working days from a certain Startdate

I've got two tables, a project table and a calendar table. The first containts a startdate and days required. The calendar table contains the usual date information, like date, dayofweek, and a column is workingday, which shows if the day is a saturday, sunday, or bank holiday (value = 0) or a regular workday (value = 1).
For a certain report I need write a stored procedure that calculates the predicted enddate by adding the number of estimated workddays needed.
Example:
**Projects**
Name Start_Planned Work_days_Required
Project A 02.05.2016 6
Calendar (04.05 is a bank holdiday)
Day Weekday Workingday
01.05.2016 7 0
02.05.2016 1 1
03.05.2016 2 1
04.05.2016 3 0
05.05.2016 4 1
06.05.2016 5 1
07.05.2016 6 0
08.05.2016 7 0
09.05.2016 1 1
10.05.2016 2 1
Let's say, the estimated number of days required is given as 6 (which leads to the predicted enddate of 10.05.2016). Is it possible to join the tables in a way, which allows me to put something like
select date as enddate_predicted
from calendar
join projects
where number_of_days = 6
I would post some more code, but I'm quite stuck on how where to start.
Thanks!
You could get all working days after your first date, then apply ROW_NUMBER() to get the number of days for each date:
SELECT Date, DayNum = ROW_NUMBER() OVER(ORDER BY Date)
FROM Calendar
WHERE IsWorkingDay = 1
AND Date >= #StartPlanned
Then it would just be a case of filtering for the 6th day:
DECLARE #StartPlanned DATE = '20160502',
#Days INT = 6;
SELECT Date
FROM ( SELECT Date, DayNum = ROW_NUMBER() OVER(ORDER BY Date)
FROM Calendar
WHERE WorkingDay = 1
AND Date >= #StartPlanned
) AS c
WHERE c.DayNum = #Days;
It's not part of the question, but for future proofing this is easier to acheive in SQL Server 2012+ with OFFSET/FETCH
DECLARE #StartPlanned DATE = '20160502',
#Days INT = 6;
SELECT Date
FROM dbo.Calendar
WHERE Date >= #StartPlanned
AND WorkingDay = 1
ORDER BY Date
OFFSET (#Days - 1) ROWS FETCH NEXT 1 ROWS ONLY
ADDENDUM
I missed the part earlier about having another table, and the comment about putting it into a cursor has prompted me to amend my answer. I would add a new column to your calendar table called WorkingDayRank:
ALTER TABLE dbo.Calendar ADD WorkingDayRank INT NULL;
GO
UPDATE c
SET WorkingDayRank = wdr
FROM ( SELECT Date, wdr = ROW_NUMBER() OVER(ORDER BY Date)
FROM dbo.Calendar
WHERE WorkingDay = 1
) AS c;
This can be done on the fly, but you will get better performance with it stored as a value, then your query becomes:
SELECT p.Name,
p.Start_Planned,
p.Work_days_Required,
EndDate = c2.Date
FROM Projects AS P
INNER JOIN dbo.Calendar AS c1
ON c1.Date = p.Start_Planned
INNER JOIN dbo.Calendar AS c2
ON c2.WorkingDayRank = c1.WorkingDayRank + p.Work_days_Required - 1;
This simply gets the working day rank of your start date, and finds the number of days ahead specified by the project by joining on WorkingDayRank (-1 because you want the end date inclusive of the range)
This will fail, if you ever plan to start your project on a non working day though, so a more robust solution might be:
SELECT p.Name,
p.Start_Planned,
p.Work_days_Required,
EndDate = c2.Date
FROM Projects AS P
CROSS APPLY
( SELECT TOP 1 c1.Date, c1.WorkingDayRank
FROM dbo.Calendar AS c1
WHERE c1.Date >= p.Start_Planned
AND c1.WorkingDay = 1
ORDER BY c1.Date
) AS c1
INNER JOIN dbo.Calendar AS c2
ON c2.WorkingDayRank = c1.WorkingDayRank + p.Work_days_Required - 1;
This uses CROSS APPLY to get the next working day on or after your project start date, then applies the same join as before.
This query returns a table with a predicted enddate for each project
select name,min(day) as predicted_enddate from (
select c.day,p.name from dbo.Calendar c
join dbo.Calendar c2 on c.day>=c2.day
join dbo.Projects p on p.start_planned<=c.day and p.start_planned<=c2.day
group by c.day,p.work_days_required,p.name
having sum(c2.workingday)=p.work_days_required
) a
group by name
--This gives me info about all projects
select p.projectname,p.Start_Planned ,c.date,
from calendar c
join
projects o
on c.date=dateadd(days,p.Work_days_Required,p.Start_Planned)
and c.isworkingday=1
now you can use CTE like below or wrap this in a procedure
;with cte
as
(
Select
p.projectnam
p.Start_Planned ,
c.date,datediff(days,p.Start_Planned,c.date) as nooffdays
from calendar c
join
projects o
on c.date=dateadd(days,p.Work_days_Required,p.Start_Planned)
and c.isworkingday=1
)
select * from cte where nooffdays=6
use below logic
CREATE TABLE #proj(Name varchar(50),Start_Planned date,
Work_days_Required int)
insert into #proj
values('Project A','02.05.2016',6)
CReATE TABLE #Calendar(Day date,Weekday int,Workingday bit)
insert into #Calendar
values('01.05.2016',7,0),
('02.05.2016',1,1),
('03.05.2016',2,1),
('04.05.2016',3,0),
('05.05.2016',4,1),
('06.05.2016',5,1),
('07.05.2016',6,0),
('08.05.2016',7,0),
('09.05.2016',1,1),
('10.05.2016',2,1)
DECLARE #req_day int = 3
DECLARE #date date = '02.05.2016'
--SELECT #req_day = Work_days_Required FROM #proj where Start_Planned = #date
select *,row_number() over(order by [day] desc) as cnt
from #Calendar
where Workingday = 1
and [Day] > #date
SELECT *
FROM
(
select *,row_number() over(order by [day] desc) as cnt
from #Calendar
where Workingday = 1
and [Day] > #date
)a
where cnt = #req_day

Checking for maximum length of consecutive days which satisfy specific condition

I have a MySQL table with the structure:
beverages_log(id, users_id, beverages_id, timestamp)
I'm trying to compute the maximum streak of consecutive days during which a user (with id 1) logs a beverage (with id 1) at least 5 times each day. I'm pretty sure that this can be done using views as follows:
CREATE or REPLACE VIEW daycounts AS
SELECT count(*) AS n, DATE(timestamp) AS d FROM beverages_log
WHERE users_id = '1' AND beverages_id = 1 GROUP BY d;
CREATE or REPLACE VIEW t AS SELECT * FROM daycounts WHERE n >= 5;
SELECT MAX(streak) AS current FROM ( SELECT DATEDIFF(MIN(c.d), a.d)+1 AS streak
FROM t AS a LEFT JOIN t AS b ON a.d = ADDDATE(b.d,1)
LEFT JOIN t AS c ON a.d <= c.d
LEFT JOIN t AS d ON c.d = ADDDATE(d.d,-1)
WHERE b.d IS NULL AND c.d IS NOT NULL AND d.d IS NULL GROUP BY a.d) allstreaks;
However, repeatedly creating views for different users every time I run this check seems pretty inefficient. Is there a way in MySQL to perform this computation in a single query, without creating views or repeatedly calling the same subqueries a bunch of times?
This solution seems to perform quite well as long as there is a composite index on users_id and beverages_id -
SELECT *
FROM (
SELECT t.*, IF(#prev + INTERVAL 1 DAY = t.d, #c := #c + 1, #c := 1) AS streak, #prev := t.d
FROM (
SELECT DATE(timestamp) AS d, COUNT(*) AS n
FROM beverages_log
WHERE users_id = 1
AND beverages_id = 1
GROUP BY DATE(timestamp)
HAVING COUNT(*) >= 5
) AS t
INNER JOIN (SELECT #prev := NULL, #c := 1) AS vars
) AS t
ORDER BY streak DESC LIMIT 1;
Why not include user_id in they daycounts view and group by user_id and date.
Also include user_id in view t.
Then when you are queering against t add the user_id to the where clause.
Then you don't have to recreate your views for every single user you just need to remember to include in your where clause.
That's a little tricky. I'd start with a view to summarize events by day:
CREATE VIEW BView AS
SELECT UserID, BevID, CAST(EventDateTime AS DATE) AS EventDate, COUNT(*) AS NumEvents
FROM beverages_log
GROUP BY UserID, BevID, CAST(EventDateTime AS DATE)
I'd then use a Dates table (just a table with one row per day; very handy to have) to examine all possible date ranges and throw out any with a gap. This will probably be slow as hell, but it's a start:
SELECT
UserID, BevID, MAX(StreakLength) AS StreakLength
FROM
(
SELECT
B1.UserID, B1.BevID, B1.EventDate AS StreakStart, DATEDIFF(DD, StartDate.Date, EndDate.Date) AS StreakLength
FROM
BView AS B1
INNER JOIN Dates AS StartDate ON B1.EventDate = StartDate.Date
INNER JOIN Dates AS EndDate ON EndDate.Date > StartDate.Date
WHERE
B1.NumEvents >= 5
-- Exclude this potential streak if there's a day with no activity
AND NOT EXISTS (SELECT * FROM Dates AS MissedDay WHERE MissedDay.Date > StartDate.Date AND MissedDay.Date <= EndDate.Date AND NOT EXISTS (SELECT * FROM BView AS B2 WHERE B1.UserID = B2.UserID AND B1.BevID = B2.BevID AND MissedDay.Date = B2.EventDate))
-- Exclude this potential streak if there's a day with less than five events
AND NOT EXISTS (SELECT * FROM BView AS B2 WHERE B1.UserID = B2.UserID AND B1.BevID = B2.BevID AND B2.EventDate > StartDate.Date AND B2.EventDate <= EndDate.Date AND B2.NumEvents < 5)
) AS X
GROUP BY
UserID, BevID

mysql day report query

The query below gives me a report of items that are out for an equipment rental company. this is a super complicated query that takes almost 20 seconds to run. This is obviously not the correct way to get the data that I'm looking for. I build this query from PHP and add in the start date of 02-01-2011 and the end date of 03-01-2011, the product code (p_code = 1) and product pool (i_pool =1). Those 4 pieces of information are passed to a PHP function and injected into the following sql to return the report I need for a calendar control displaying how many items are out. My question is: Is there any way to simplify or do this better, or run more efficiently, using better joins or a better way to display the individual days.
SELECT DISTINCT reportdays.reportday, count(*)
FROM
(SELECT '2011-02-01' + INTERVAL a + b DAY reportday
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m
WHERE '2011-02-01' + INTERVAL a + b DAY < '2011-03-01'
ORDER BY a + b) as reportdays
JOIN rental_inv as line
ON DATE(FROM_UNIXTIME(line.ri_delivery_dte)) <= reportdays.reportday
AND DATE(FROM_UNIXTIME(line.ri_pickup_dte)) >= reportdays.reportday
LEFT OUTER JOIN rental_in as rent on line.ri_num = rent.ri_num
LEFT OUTER JOIN rental_cancels cancelled on rent.ri_num = cancelled.ri_num
LEFT OUTER JOIN inv inventory on line.i_num = inventory.i_num
LEFT OUTER JOIN product ON inventory.p_code = product.p_code
WHERE rent.ri_extend = 0 -- disregard extended rentals
AND cancelled.ri_num is null -- disregard cancelled rentals
AND inventory.p_code = 1
AND inventory.i_pool = 1
GROUP BY reportdays.reportday
If there is any other information needed, let me know and I'll post it.
You can use:
SELECT DATE(ri_delivery) as day,
count(*) as itemsout,
FROM rental_inv
GROUP BY day;
I'm not sure if you need this or a different thing.
SELECT dates.day, count (*)
FROM rental_inv line
INNER JOIN (SELECT DATE(ri_delivery_dte) as day FROM rental_inv
WHERE ri_delivery_dte >= '2011/02/01'
AND ri_delivery_dte <= '2011/02/28'
GROUP BY day
UNION
SELECT DATE(ri_pickup_dte) as day FROM rental_inv
WHERE ri_pickup_dte >= '2011/02/01'
AND ri_pickup_dte <= '2011/02/28'
GROUP BY day) dates
ON line.ri_delivery_dte <= dates.day and line.ri_pickup_dte >= dates.day
LEFT JOIN rental_cancels canc on line.ri_num = canc.ri_num
LEFT JOIN rental_in rent on line.ri_num = rent.ri_num
WHERE canc.ri_num is null
AND rent.ri_extend = 0
GROUP BY dates.day
to find all days:
SELECT DATE(IFNULL(ri_delivery,ri_pickup)) AS date FROM rental_inv AS dateindex WHERE [YEAR-MONTH-1] <= ri_delivery <= LAST_DAY([YEAR-MONTH-1]) OR [YEAR-MONTH-1] <= ri_pickup <= LAST_DAY([YEAR-MONTH-1]) GROUP BY date HAVING NOT ISNULL(date)
to find items out
SELECT COUNT(id) FROM rental_inv WHERE ri_pickup = [DATE];
to find items in
SELECT COUNT(id) FROM rental_inv WHERE ri_delivery = [DATE];
to find balance
SELECT COUNT(out.id) - COUNT(in.id) FROM rental_inv AS out INNER JOIN rental_inv AS in
ON DATE(out.ri_pickup) = DATE(in.ri_delivery) WHERE out.ri_pickup = [DATE] OR in.ri_delivery = [DATE]
You probably can join up everything but since its procedure its more clear;
I am not sure if this would be the exact answer to your problem but I would do something like this I guess. (I didn't use any SQL editor so u need to check syntax I guess)
SELECT
reportdays.d3 as d,
( COALESCE(outgoing.c1,0) - COALESCE(incoming.c2,0) ) as c
FROM
-- get report dates
(
SELECT DATE(FROM_UNIXTIME(COALESCE(l3.ri_delivery_dte, l3.ri_pickup_dte)) d3
FROM rental_inv l3
WHERE
(l3.ri_delivery_dte >= UNIX_TIMESTAMP('2011-02-01')
AND l3.ri_delivery_dte < UNIX_TIMESTAMP('2011-03-01'))
OR (l3.ri_pickup_dte >= UNIX_TIMESTAMP('2011-02-01')
AND l3.ri_pickup_dte < UNIX_TIMESTAMP('2011-03-01'))
GROUP BY d3
) as reportdays
-- get outgoing
LEFT JOIN (
SELECT DATE(FROM_UNIXTIME(l1.ri_delivery_dte)) as d1, count(*) as c1
FROM rental_inv l1
LEFT JOIN rental_cancels canc1 on l.ri_num = canc1.ri_num
LEFT JOIN rental_in rent1 on l.ri_num = rent1.ri_num
WHERE
l1.ri_delivery_dte >= UNIX_TIMESTAMP('2011-02-01')
AND l1.ri_delivery_dte < UNIX_TIMESTAMP('2011-03-01')
AND canc1.ri_num is null
AND rent1.ri_extend = 0
GROUP BY d1
) as outgoing ON reportdays.d3 = outgoing.d1
-- get incoming
LEFT JOIN (
SELECT DATE(FROM_UNIXTIME(l2.ri_pickup_dte)) as d2, count(*) as c2
FROM rental_inv l2
LEFT JOIN rental_cancels canc2 on l2.ri_num = canc2.ri_num
LEFT JOIN rental_in rent2 on l2.ri_num = rent2.ri_num
WHERE
l2.ri_pickup_dte >= UNIX_TIMESTAMP('2011-02-01')
AND l2.ri_pickup_dte < UNIX_TIMESTAMP('2011-03-01')
AND canc2.ri_num is null
AND rent2.ri_extend = 0
GROUP BY d2
) as incoming ON reportdays.d3 = incoming.d2