Updating Due Date based on Invoice Date and Vendor - sql

I am using DocuWare Workflow Designer (uses SQL) to fill in the due date based on the invoice date and vendor name. In the code below I am trying to have it add 15 days to the invoice date if the vendor is "Hueber - Jones & Coontz" otherwise have the Due Date equal the Invoice Date. The code errors out currently and makes the Due Date equal todays date. I am not able to bring up where in the code its failing. Everything in brackets is references to predefined variables in DocuWare.
SELECT [DW_INVOICE_DATE] FROM [AP] WHERE IF [DW_VENDOR_NAME] = 'HUEBER - JONES & COONTZ' [DW_DUE_DATE] = DATEADD(DD,15,[DW_INVOICE_DATE] ELSE [DW_DUE_DATE] = [DW_INVOICE_DATE]
Thanks in advance.

I don't know how DocuWare works, it it's just simple SQL this is the command:
UPDATE [AP]
SET [DW_DUE_DATE] = (CASE
WHEN [DW_VENDOR_NAME] = 'HUEBER - JONES & COONTZ' THEN DATEADD(DD,15,[DW_INVOICE_DATE])
ELSE [DW_INVOICE_DATE]
END)

Related

Create Auto Repeated Records by Time

I just new in access, and I have to face up the DB everyday. In this case, I create a form to record scedule of planned maintenance (next I call it "PM") which has variaties divided of time by week, month and year. Every PM that has been created, it has an unique number of PM. The number is as follows : 162/PNT/PM/06/2020. The number was containing with : "unique number"/"PM's area"/"type of maintenance"/"month"/"year".
Then, is there a way to create records repeatly based on time or previous PM schedule with the same content?
For an example :
I create a monthly PM schedule which the number is 001/PNT/PM/01/2020 on 20-Jan-2020. When I press the save button (or copy schedule button), the record will copying (creating) to 20-Feb-2020 with changed PM's number to 002/PNT/PM/02/2020 automatically.
Thanks for anyone who wants to help me.
June is right. Use a table like this:
ID - Long
PNT - Short Text
PM - Short Text
StartDate - DateTime
and a query to assemble the code:
SELECT
Maintenance.ID,
Maintenance.PNT,
Maintenance.PM,
Maintenance.StartDate,
Format([ID],"000") & "/" & [PNT] & "/" & [PM] & "/" & Format([StartDate],"mm\/ddyy") AS Code
FROM
Maintenance;
Output:
Now, to create the next record, use:
NextID = ID + 1
NextDate = DateAdd("m", 1, StartDate)

Find changes made in PGSQL table using SQL in Excel VBA

Is it possible to create an SQL query to compare a field within a single table to see if a change has been made and if possible list the before and after?
I have the following SQL query written in Excel 2010 VBA, which connects to an Oracle PostGreSQL database
Dim au As String
au = "SELECT id, priority, flag, code " _
& "FROM hist WHERE ( aud_dt >= '18/05/2020' AND aud_dt <='18/05/2020' ) " _
Set rs = conn.Execute(au)
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
.Refresh
End With
Where fields include:
"priority" is the field that I'd like to check for changes which will
be a single number between 0-9
"code" is the record that has been
assigned the priority and is a mixture of numbers and letters up to 7
characters
"flag" shows a 1 as the active record, and 2 as an edited
record
"id" refers to the user account
I'd ideally like to end up with something like: id | priority | flag | priority_old | flag_old | code
Which should show the before and after changes to the priority. If the record shows priority=3 and flag=2 and code=Ab12, there must also be record with a 1 flag, as that is now the active record. If it has the same priority number for the code I'm not interested in it as that just means something else was changed instead as I have not listed all the column fields.
If the active record now shows priority=4, flag=1 and code=Ab12, that would be exactly the record I need to see.
Consider a self-join query (possibly you need to adjust date filter in WHERE depending on when items change):
SELECT h1.id, h1.priority, h1.flag,
h2.priority AS priority_old, h2.flag AS flag_old, h1.code
FROM hist h1
LEFT JOIN hist h2
ON h1.code = h2.code
AND h1.priority <> h2.priority
AND h1.flag = 1
AND h2.flag <> 1
WHERE (aud_dt >= '2020-05-18' AND aud_dt <='2020-05-18')

Compare data in the same table

I have a table that stores monthly data and I would like to create a comparison between the quantity movement within a period.
Here is an example of the table
.
The SQL statement below is meant to return any changes that has happened within a period - any fund/policy partial or total loss as well as partial or total gain. I have been battling with it for a while - any help would be well appreciated.
I currently have 5 sets of unions - (where the policies and funds match and there's a difference in quantities held, where the policies exist in the previous and not in the current and vice versa and where the securities exist in the previous and not in the current and vice versa) but the other unions work save for the last couple (where the securities exist in the previous and not in the current and vice versa). It doesn't seem to return every occurrence.
SELECT distinct pc.[Client]
,pc.Policy
,cast(pc.Qty as decimal) AS CurrQ
,0 AS PrevQ
,cast(pc.Qty as decimal) - 0 AS QtyDiff
,CASE WHEN cast(pc.Qty as decimal) - 0 > 0 THEN 'Bought Units'
WHEN cast(pc.Qty as decimal) - 0 < 0 THEN 'Sold Units'
ELSE 'Unknown'
END AS TransactionType
,convert(varchar,cast(pc.[ValDate] as date),103) AS CurrValDate
,'' AS PrevValDate
FROM table pc
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103)
AND pc.Policy IN (SELECT policy
FROM table
WHERE convert(varchar(10),[ValDate],103) = convert(varchar(10),getdate()-1,103)
AND pc.[Fund] NOT IN (SELECT PM.[Fund]
FROM table pc
LEFT JOIN table pm ON pc.policy = pm.policy
WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103))
AND convert(varchar,cast(pm.[ValDate] as date),103) = convert(varchar,getdate()-1,103))
As #Larnu rightly mentioned in the comment section, the extra conditions in the query changed the run from a LEFT JOIN to an INNER JOIN. I changed the code to have policy, fund and date in the ON clause:
FROM table pc
LEFT JOIN table pm ON (pc.policy = pm.policy
AND pc.fund = pm.fund
AND pc.[ValDate]-1 = pm.[ValDate])
and got rid of the sub queries.
Thanks again Larnu.

I want to update values in column, based on condition that need to compare data from another table

I need help on one case in SQL, so I have to fill one column DIFFERENCE with 'Above' or 'Below' in table CLIENTS, if the date in other column in table - DOCUMENT is above or below 4 months from now. I tried with this
UPDATE CLIENTS
SET DIFFERENCE = CASE WHEN MONTHS_BETWEEN(TO_DATE((SELECT DATA FROM DOCUMENT, CLIENTS WHERE DOCUMENT.ID_CLIENT=CLIENTS.ID_CLIENT ),'DD.MM.YYYY'),TO_DATE(SYSDATE,'DD.MM.YYYY')) < 4 THEN 'Below' ELSE 'Above' END
but it returns lot of values, so I tried to JOIN the tables and
UPDATE CLIENTS
SET DIFFERENCE = CASE WHEN MONTHS_BETWEEN(TO_DATE(DATA,'DD.MM.YYYY'),TO_DATE(SYSDATE,'DD.MM.YYYY')) < 4 THEN 'Below' ELSE 'Above' END
FROM CLIENTS JOIN DOCUMENT
ON DOCUMENT.ID_CLIENT=CLIENTS.ID_CLIENT
but this time says Not properly ended.
I'm working with Oracle db.
Please if you see the answer, write me!
Thank you in advance!
SELECT CLIENTS.ID_CLIENT,MIN(DOCUMENT.DATA) AS "DATA"
FROM DOCUMENT,CLIENTS
WHERE CLIENTS.ID_CLIENT=DOCUMENT.ID_CLIENT
GROUP BY CLIENTS.ID_CLIENT
and some of the results:
ID_CLIENT DATA
54 01/23/2014
57 01/23/2014
78 01/23/2014
87 01/24/2014
91 01/24/2014
I found the solution,
UPDATE CLIENTS
SET DIFFERENCE = CASE WHEN MONTHS_BETWEEN(TO_DATE((SELECT MIN(DATA) FROM DOCUMENT, CLIENTS WHERE DOCUMENT.ID_CLIENT=CLIENTS.ID_CLIENT),'MM.DD.YYYY'),TO_DATE(SYSDATE,'MM.DD.YYYY')) < 4 THEN 'Below' ELSE 'Above' END
The mistake was 'MM.DD.YYYY' ... first I used 'DD.MM.YYYY' - very stupid mistake!
Thanks for all the answers! ekad YOU really helped me!!!
Instead of joining the tables, you need to check whether there's any related documents with DATA more than 4 months from now using EXISTS. It also seems that DOCUMENT.DATA is a varchar and the value is set using mm/dd/yyyy format, so you need to change the second parameter of TO_DATE function to MM/DD/YYYY
UPDATE CLIENTS
SET DIFFERENCE = CASE WHEN EXISTS
(SELECT 1 FROM DOCUMENT
WHERE ID_CLIENT = CLIENTS.ID_CLIENT
AND MONTHS_BETWEEN(TO_DATE(DATA,'MM/DD/YYYY'),SYSDATE) > 4)
THEN 'Above'
ELSE 'Below' END

How would I translate this SQL query into a Raven Map/Reduce query?

Following on from my previous question at When is a groupby query evaluated in RavenDB? I decided to completely restructure the data into a format that is theoretically easier to query on.
Having now created the new data structure, I am struggling to find how to query it.
It took me 30 seconds to write the following SQL query which gives me exactly the results I need:
SELECT GroupCompanyId, AccountCurrency, AccountName, DATEPART(year, Date) AS Year,
(SELECT SUM(Debit) AS Expr1
FROM Transactions AS T2
WHERE (T1.GroupCompanyId = GroupCompanyId) AND (T1.AccountCurrency = AccountCurrency) AND (T1.AccountName = AccountName) AND (DATEPART(year,
Date) < DATEPART(year, T1.Date))) AS OpeningDebits,
(SELECT SUM(Credit) AS Expr1
FROM Transactions AS T2
WHERE (T1.GroupCompanyId = GroupCompanyId) AND (T1.AccountCurrency = AccountCurrency) AND (T1.AccountName = AccountName) AND (DATEPART(year,
Date) < DATEPART(year, T1.Date))) AS OpeningCredits, SUM(Debit) AS Db, SUM(Credit) AS Cr
FROM Transactions AS T1
WHERE (DATEPART(year, Date) = 2011)
GROUP BY GroupCompanyId, AccountCurrency, AccountName, DATEPART(year, Date)
ORDER BY GroupCompanyId, AccountCurrency, Year, AccountName
So far I have got the Map/Reduce as follows, which from Studio appears to give the correct results - i.e. it breaks down and groups the data by date.
public Transactions_ByDailyBalance()
{
Map = transactions => from transaction in transactions
select new
{
transaction.GroupCompanyId,
transaction.AccountCurrency,
transaction.Account.Category,
transaction.Account.GroupType,
transaction.AccountId,
transaction.AccountName,
transaction.Date,
transaction.Debit,
transaction.Credit,
};
Reduce = results => from result in results
group result by new
{
result.GroupCompanyId,
result.AccountCurrency,
result.Category,
result.GroupType,
result.AccountId,
result.AccountName,
result.Date,
}
into g
select new
{
GroupCompanyId = g.Select(x=>x.GroupCompanyId).FirstOrDefault(),
AccountCurrency = g.Select(x=>x.AccountCurrency).FirstOrDefault(),
Category=g.Select(x=>x.Category).FirstOrDefault(),
GroupType=g.Select(x=>x.GroupType).FirstOrDefault(),
AccountId = g.Select(x=>x.AccountId).FirstOrDefault(),
AccountName=g.Select(x=>x.AccountName).FirstOrDefault(),
Date=g.Select(x=>x.Date).FirstOrDefault(),
Debit=g.Sum(x=>x.Debit),
Credit=g.Sum(x=>x.Credit)
};
Index(x=>x.GroupCompanyId,FieldIndexing.Analyzed);
Index(x=>x.AccountCurrency,FieldIndexing.Analyzed);
Index(x=>x.Category,FieldIndexing.Analyzed);
Index(x=>x.AccountId,FieldIndexing.Analyzed);
Index(x=>x.AccountName,FieldIndexing.Analyzed);
Index(x=>x.Date,FieldIndexing.Analyzed);
}
}
However, I can't work out how to query the data at one go.
I need the opening balance as well as the period balance, so I ended up writing this query which takes as a parameter the account. Following on from Oren's comments to my previous question, that I was mixing Linq with Lucene query, having rewritten the query, I've basically ended up again with a mixed query.
Even though I am showing in the SQL query above that I am filtering by year, in fact I need to be able to determine the current balance from any day.
private LedgerBalanceDto GetAccountBalance(BaseAccountCode account, DateTime periodFrom, DateTime periodTo, string queryName)
{
using (var session = MvcApplication.RavenSession)
{
var query = session.Query<Transactions_ByDailyBalance.Result, Transactions_ByDailyBalance>()
.Where(c=>c.AccountId==account.Id && c.Date>=periodFrom && c.Date<=periodTo)
.OrderBy(c=>c.Date)
.ToList();
var debits = query.Sum(c => c.Debit);
var credits = query.Sum(c => c.Credit);
var ledgerBalanceDto = new LedgerBalanceDto
{
Account = account,
Credits = credits,
Debits = debits,
Currency = account.Currency,
CurrencySymbol = account.CurrencySymbol,
Name = queryName,
PeriodFrom = periodFrom,
PeriodTo = periodTo
};
return ledgerBalanceDto;
}
}
Required result:
GroupCompanyId AccountCurrency AccountName Year OpeningDebits OpeningCredits Db Cr
Groupcompanies-2 EUR Customer 1 2011 148584.2393 125869.91 10297.6891 28023.98
Groupcompanies-2 EUR Customer 2 2011 236818.0054 233671.55 50959.85 54323.38
Groupcompanies-2 USD Customer 3 2011 69426.11761 23516.3776 10626.75 0
Groupcompanies-2 USD Customer 4 2011 530587.9223 474960.51 97463.544 131497.16
Groupcompanies-2 USD Customer 5 2011 29542.391 28850.19 4023.688 4231.388
Any suggestions would be greatly appreciated
Jeremy
In answer to the comment
I basically ended up doing pretty much the same thing. Actually, I wrote an index that does it in only two hits - once for the opening balance and again for the period balance. This is almost instantaneous for grouping by the account name, category etc.
However my problem now is getting a daily running balance for the individual account. If I bring down all the data for the account and the period, its not a problem - I can sum the balance on the client, however, when the data is paged, and the debits and credits are grouped by Date and Id, the paging cuts across the date, so the opening/closing balance is not correct.
Page 1
Opening balance until 26/7/12 = 0
25/7/12 Acct1 Db 100 Cr 0 Bal +100 Runn Bal +100
26/7/12 Acct1 Db 100 Cr 0 Bal +100 Runn Bal +200
26/7/12 Acct1 Db 200 Cr 0 Bal +200 Runn Bal +400
Closing balance until 26/7/12 = +400
Page 2
Opening balance until 26/7/12 = +450 (this is wrong - it should be the balance at the end of Page 1, but it is the balance until the 26/7/12 - i.e. includes the first item on Page 2)
26/7/12 Acct1 Db 50 Cr 0 Bal +50 Runn Bal +500 (should be +450)
27/7/12 Acct1 Db 60 Cr 0 Bal +60 Runn Bal +560 (should be +510)
I just can't think up an algorithm to handle this.
Any ideas?
Hi this is a problem I have also faced recently with RavenDb when I needed to retrieve rolling balances as at any imaginable date. I never found a way of doing this all in one go but I managed reduce the amount of documents that I needed to pull back in order to calculate the rolling balance.
I did this by writing multiple map reduce indexes that summed up the value of transactions within specific periods:
My First Summed up the value of all transactions grouped at the year level
My Second index Summed up the value of all transactions at the Day level
So if someone wanted their account balance As At 1st June 2012 I would:
Use the Year level Map-reduce index to get the Value of transactions for years up to 2012 and summed them together (so if transactions started being captured in 2009 I should be pulling back 3 documents)
Use the Day level Map-reduce index to get all documents from the start of the year and the 1st of June
I then Added the Day totals to the year totals for my final rolling balance (I could have also had a monthly map reduce as well but didn't bother).
Anyway not as quick as in SQL but it was the best alternative I could come up with to avoid bringing back every single transaction