Zoho Reports: SQL Query - Finding date and number of days - sql

Problem Statement: I need to find out Over Due start date and from that i need to calculate number of Over due days. I know how to do for Over due days count, but i am not able to find a way to figure out for Over due start date.
Example: Let us say a customer did not pay for 4th November 2017, 4th December 2017, 4th Jan 2018, 4th Feb 2018. Now for these There were 4 Zero collection records placed in Collections table and 4 records placed in Over Due Collections table with D Flag. Now on 8th Feb Customer Paid an installment then the respective payment record has been placed in Collections table and another record in Over due collections with C flag. Since this payment gets adjusted for 4th November 2017 the Over due start date will be 4th December. Suppose if the customer did not pay then it will be 4th November 2017 as the Over due start date.
I have tables as follows for a Loan Management System:
Schedule (Payment Schedule): Which will have all the Installments, with the dates adn the respective amounts to be paid for each month.
Schema: LoanNo, Schedule Date, Installment No, Principle, Interest.
Collections (Payment Collections) for each month which has been collected. Suppose if the payment not received, A record placed with the respective date and with Zero amount. and another record will be placed in Over due collections table with D flag with the respective amounts. If there is any collection happens, then another record will be inserted with the flag C which represents collections.
Schema: LoanNo, PaymentReceived Date, Principle, Interest
Over Due Collections (Which there will be a record placed if there is a Due)
Schema: LoanID, Flag(D/C), Date, Principle, Interest
Please do suggest and guide me to write a proper query for this

it's interesting yet easy problem. you can tackle by calculating running sum of the amount and then compare with total payments by the customer. Take all the records having running sum greater than total payment. and choose minimum date out of it.
let me know if require further help I will give you SQL query. But you should try by your own
Edit 1
this will provide you running_sum
_______Subquery1_______
select a.LoanNO,a.Scheduledate,a.Amount,sum(b.amount)run_sum from
Paymentschedule a
join PayamentSchedule b
on a.LoanNo=b.LoanNo and a.ScheduleDate>b.ScheduleDate and
a.ScheduleDate<=now() group by 1,2,3
total collection against loan
_______subquery 2_____
select LoanNo,sum(amount)total collection from collection group by 1
now
select a.LoanNo,min(ScheduleDate) overduestartdate from subquery1 join subquery2 on
a.LoanNO=b.LoanNO
and a.run_sum>b.Collection group by 1
modify according to your schema

Related

Tying in public purchase records

I'm trying to get a list of purchases for work. Currently, what we're doing is tracing product orders based on what our customers have said they've bought. For instance, Steve says he has bought iPhones on the 3rd Jan 2022, the 15th Dec 2021 and the 1st of Nov 2021.
What I'm currently doing is a very arduous task - three separate queries, extracting them all, then removing duplicates in Excel to then analyze the account ID's that have bought on those three dates.
This in of itself takes time, but also, some customers buy 5, 7, 10 products etc so it can become quite difficult.
select tt.order_time, tt.from, tt.to, tt.value/1e9, tt.orderID
from transactiontable tt
where right(tt.data::varchar,8) = '9092fcb5'
and left(tt.data::varchar, 10) in ('\xfb3bdb41', '\x7ff36ab5')
and tt.contract_address = '\9092fcb5'
and tt.order_time between '2022-05-09 00:00' and '2022-05-09 23:59'
Does anyone have any help on how I can essentially take X number of queries and then only show me the distanct "from" addresses for each overall query?
Thanks!

Rolling Balances with Allocated Transactions

I am needing to Calculate the start/end Balances by day for each Site/Department.
I have a source table call it “Source” that has the following fields:
Site
Department
Date
Full_Income
Income_To_Allocate
Payments_To_Allocate
There are 4 Sites (SiteA/SiteB/SiteC/SiteD), Sites B-D have only 1 department and Site A has 10 departments.
This table is “mostly” a daily summary. I say “mostly” as the daily detail from 2018 was lost and instead we just have the monthly summary inputted as one entry on the last day of the month. For 2018 there is only data going back to September. From 1/1/2019 the summary is actually daily.
Any Income in the Full_Income field will be given to that Site/Department at 100% value.
Any Income in the Income_To_Allocate field will be spread among all the Site/Departments using the below logic:
(
(Prior_Month_Site_Department_ Balance+ This_Month_Site_Department_Full_Income)
/
(Prior_Month_All_Department_Balance + This_Month_All_Department_Full_Income)
)
*
(This_Month_All_Department_Income_to_Allocate)
Any Payments in the Payments_to Allocate) field will be spread among all the Site/Departments using the below logic:
(
(Prior_Month_Site_Department_ Balance+ This_Month_Site_Department_Full_Income)
/
(Prior_Month_All_Department_Balance + This_Month_All_Department_Full_Income)
)
*
(This_Month_All_Department_Payments_to_Allocate)
The idea behind these pieces of logic is to spread the allocated pieces based on the % of business each Site/Department did when looking at the Full_Income data.
The Balance would be calculated with this logic:
Start Balance:
Prior day Ending Balance
Ending Balance:
Prior day Ending Balance + (Site_Department_Full_Income) + (Site_Department_Allocated_Income)- (SiteDepartment_Allocated_Income)
I have tried to do things using the lag function to grab the prior info that I am needing for these calculations. I always get real close but I always wind up stuck on the fact the Ending Balance is calculated using the post spread values for the allocated income and reseeds while the calculation for the spread is using the prior month balance info. This ends up being almost circular logic but with a finite start point. I am at a loss for how to make this work.
I am using SQL Server 2012. Let me know if you need any more details.

Filter PowerPivot based on multiple Date Criteria

I am trying to apply some Time Intelligence functions in my PowerPivot workbook concerning projects and money received for them. I have three relevant tables; Matters, Payments, and a Date Table.
Each matter has a creationDate, and a closureDate(from a linked table). Likewise, each payment has a date. I have reporting set up decently, but am now trying to use Time intelligence to filter this a bit more clearly.
How can I set a PowerPivot Pivot Table up so that the only Matters which show are those which existed within the period selected. e.g. If I select a slicer for 2014, I don't want to show a matter created in 2015, or one which was closed in 2013. The matter should have been active during the period specified.
Is this possible?
You want to show all the matters EXCEPT those where the CreationDate is after the upper limit of the date range you are looking at or the ClosureDate is before the lower limit of the date range you are looking at.
Assuming you have a data structure like this, where the left-hand table is the Matters and the right-hand one is the Payments:
If you have a calculated field called [Total Payments] that just adds up all the payments in the Payments table, a formula similar to this would work:-
[Payment in Range]:=IF(OR(MIN(Matters[Creation Date])>MAX('Reporting Dates'[Date]),MAX(Matters[Closure Date])<MIN('Reporting Dates'[Date])),BLANK(),[Total Payments])
Here is the result with one month selected in the timeline:
Or with one year selected in the year slicer:
NOTE: in my example, I have used a disconnected date table.
Also, you will see that the Grand Total adds up all the payments because it takes the lowest of all the creation dates and the highest of all the closure dates to determine whether to show a total payment value. If it is important that the Grand Total shows correctly, then an additional measure is required:
[Fixed Totals Payment in Range]:=IF(COUNTROWS(VALUES(Matters[Matter]))=1,[Payment in Range],SUMX(VALUES(Matters[Matter]),[Payment in Range]))
Replace the [Payment in Range] in your pivot table with this new measure and the totals will show correctly, however, this will only work if Matters[Matter] is used as one of the fields in the pivot table.
Use filters & the calculate function.
So, if you're Summing payments, it would look like.....
Payments 2014:= CALCULATE( SUM([Payments]), DateTable[Year]=2014)
The Sum function takes the entirety of payments & the filter function will only capture payments w/in 2014, based on the data connected to your date table.

Best practice for keeping historical data in SQL (for SSAS Cube use)

I am working on an Hotel DB, and the booking table changes a lot since people book and cancel reservation all the time. Trying to find out the best way to convert the booking table to a fact table in SSAS. I want to be able to get the right statsics from it.
For example: if a client X booked a room on Sep 20th for Dec 20th and canceled the order on Oct 20th. If I run the cube on the month of September (run it in Nov) and I want to see how many rooms got booked in the month of Sep, the order X made should be counted in the sum.
However, if I run the cube for YTD calculation (run it in Nov), the order shouldn't be counted in the sum.
I was thinking about inserting the updates to the same fact table every night, and in addition to the booking number (unique key) and add revision column to the table. So going back to the example, let say client X booking number is 1234, the first time I enter it to the table will get revision 0, in Oct when I add the cancellation record, it will get revision 1 (of course with timestamp on the row).
Now, if I want to look on any piroed of time, I can take it by the timestamp and look at the MAX(revision).
Does it make sense? Any ideas?
NOTE: I gave the example of cancelling the order, but we want to track another statistics.
Another option I read about is partitioning the cubes, but do I partition the entire table. I want to be able to add changes every night. Will I need to partition the entire table every night? it's a huge table.
One way to handle this is to insert records in your fact table for bookings and cancellations. You don't need to look at the max(revision) - cubes are all about aggregation.
If your table looks like this:
booking number, date, rooms booked
You can enter data like this:
00001, 9/10, 1
00002, 9/12, 1
00001, 10/5, -1
Then your YTDs will always have information accurate as of whatever month you're looking at. Simply sum up the booked rooms.

How do I calculate a profit for each month in MS Access?

I'm quite new to access and I am currently in the process of making a database for my company.
I have a 'Jobs' table with these fields in:
Job No.
Year Initiated
Month Initiated
Company ID
Job Description
Amount Quoted
Amount to Invoice
Invoice Number
Completed By
Cost
Profit
What I want to know Is what is the best way/ how do I calculate either in a form or query the overall profit for each month?
Please help, the database is really coming along, apart from this is well entruely stuck on.
You want to find all rows matching a specific year / month, and add together all the profit entries for that month to get a total?
If so, try this :
select sum(profit) from Jobs where year = 2013 and month = 02
Or, if you want to retrieve this information for all months in one go, try this :
select year, month, sum(profit) from Jobs group by year, month