how to get credit and debt based on union of two tables - sql

today i faced a rather weird problem while i was coding and i really have no idea how to fix this, this is the code i wrote
select kv.third_party, --THIRD PARTY CODE
kv.NUM_PUROR, --PURCHASE CODE
kv.DTACN_COD_ACN_DTACN --ACCOUNT CODE
SUM(DEBT) DEBT,
SUM(CREDIT) CREDIT
FROM(SELECT ACNVI.third_party,
ACNVI.NUM_PUROR,
ACNVI.DTACN_COD_ACN_DTACN
SUM(ACNVI.AMN_DBT_ACNVI - ACNVI.AMN_CRD_ACNVI) DEBT,
0 CREDIT
FROM BFS_ACCOUNT_COUVHER_ITEMS ACNVI
WHERE TO_CHAR(ACNVI.ACVOH_DAT_DCM_ACVOH,'YYYY') BETWEEN '1990' AND '2000'
AND SUBSTR(ACNVI.DTACN_COD_ACN_DTACN,1,4) IN ('3102')
GROUP BY ACNVI.third_party,
ACNVI.NUM_PUROR,
ACNVI.DTACN_COD_ACN_DTACN,
SUBSTR(ACNVI.DTACN_COD_ACN_DTACN,1,4)
HAVING SUM(ACNVI.AMN_DBT_ACNVI - ANCVI.AMN_CRD_ACNVI)>0
UNION
SELECT ACNVI.third_party,
ACNVI.NUM_PUROR,
ACNVI.DTACN_COD_ACN_DTACN
0 DEBT,
SUM(ACNVI.AMN_CRD_ACNVI- ACNVI.AMN_DBT_ACNVI ) CREDIT
FROM BFS_ACCOUNT_COUVHER_ITEMS ACNVI
WHERE TO_CHAR(ACNVI.ACVOH_DAT_DCM_ACVOH,'YYYY') BETWEEN '1990' AND '2000'
AND SUBSTR(ACNVI.DTACN_COD_ACN_DTACN,1,4) IN ('3102')
GROUP BY ACNVI.third_party,
ACNVI.NUM_PUROR,
ACNVI.DTACN_COD_ACN_DTACN,
SUBSTR(ACNVI.DTACN_COD_ACN_DTACN,1,4)
HAVING SUM(ACNVI.AMN_CRD_ACNVI- ACNVI.AMN_DBT_ACNVI)>0) KV
*****
GROUP BY KV.THIRD_PART,KV.NUM_PUROR,KV.DTACN_COD_ACN_DTACN
ok so the above is the code i wrote and what i want which i dunno how to do is this: i want to have something like below in the star area
"having sum(debt)=sum(credit)"
but when i write that the table will be empty.
parameter meanings:
#amn_dbt_acnvi --- amount of debt for each account
#amn_crd_acnvi --- amount of credit for each account
#(amn_dbt_acnvi-amn_crd_acnvi) --- account balance (i wrote two kinds in the code because i want to have one balance on debt and one balance on credit)
#bfs_account_voucher_items ---this is the table with required info (debt,credit,third_party code ,etc.)
needed result is something like this for example :
row#1 : third_party: a // num_puror: b//account_code: 310201//debt : 100 credit :0
row#2 : third_party: a // num_puror: b//account_code: 310203//debt : 0
credit:100
subtract of them should be 0

Related

How to group on an aggregated data

so I've to gather the data from the table such that
1.Group each order by shipment type.
2.Filter orders for which sum of sales at shipping group level is less than $35 however overall sales is greater than $35.
For eg: If an order has two shipping groups: S2H and SDD.
Then:
S2H = $20
SDD = $25
Order total = $45
In the above example the individual shipment total is less than $35, however order total is greater than $35.
I've tried till here and would like to know how can I move forward from here to get the desirable date:
SELECT
(CASE WHEN Sales > 35 AND Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Above_SDD_Order,
(CASE WHEN Sales <= 35 AND  Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Below_SDD_Order,
(CASE WHEN Sales > 35 AND Digital = 1 AND SDD = 1 AND BOPS = 0 AND S2H = 1 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Above_SDD_S2H_Digital_Order,
(CASE WHEN Sales <= 35 AND Digital = 1 AND SDD = 1 AND BOPS = 0 AND S2H = 1 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Below_SDD_S2H_Digital_Order,
(CASE WHEN Sales > 35 AND Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 1 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Above_S2H_SDD_Order,
(CASE WHEN Sales <= 35 AND Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 1 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Below_SDD_S2H_Order,
(CASE WHEN Sales > 35 AND Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 1 THEN order_no
      ELSE NULL END) AS Above_Preorder_SDD_Order,
(CASE WHEN Sales <= 35 AND Digital = 0 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 1 THEN order_no
      ELSE NULL END) AS Below_Preorder_SDD_Order,
(CASE WHEN Sales <= 35 AND Digital = 1 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Below_Digital_SDD_Order,
(CASE WHEN Sales > 35 AND Digital = 1 AND SDD = 1 AND BOPS = 0 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END )AS Above_Digital_SDD_Order,
(CASE WHEN Sales <= 35 AND Digital = 0 AND SDD = 1 AND BOPS = 1 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Below_BOPS_SDD_Order,
(CASE WHEN Sales > 35 AND Digital = 0 AND SDD = 1 AND BOPS = 1 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END) AS Above_BOPS_SDD_Order,
(CASE WHEN Sales <= 35 AND Digital = 1 AND SDD = 1 AND BOPS = 1 AND S2H = 0 AND PREORDER = 0 THEN order_no
      ELSE NULL END )AS Below_Digital_BOPS_SDD_Order,
(CASE WHEN Sales > 35 AND Digital = 1 AND SDD = 1 AND BOPS = 1 AND S2H = 0 AND PREORDER = 0 THEN order_no ELSE NULL END )AS Above_Digital_BOPS_SDD_Order
FROM 
(SELECT order_no,
MAX(CASE WHEN (Shipping_Group = 'DIGITAL_GIFT_CARD' OR Shipping_Group = 'DIGITAL' OR Shipping_Group = 'GAME_INFORMER_DIGITAL' OR Shipping_Group = 'LOYALTY') THEN 1 ELSE 0 END ) AS Digital,
MAX(CASE WHEN Shipping_Group = 'GAME_INFORMER_PHYSICAL' OR Shipping_Group = 'PHYSICAL' THEN 1 ELSE 0 END) AS S2H,
MAX(CASE WHEN Shipping_Group = 'PHYSICAL_PREORDER' OR Shipping_Group = 'DIGITAL_PREORDER' OR Shipping_Group = 'PICKUP_PREORDER' THEN 1 ELSE 0 END ) AS Preorder,    
MAX(CASE WHEN Shipping_Group = 'PICKUP' THEN 1 ELSE 0 END ) AS BOPS,
MAX(CASE WHEN Shipping_Group = 'SDD' THEN 1 ELSE 0 END) AS SDD,
SUM(pl_net_price) as Sales
From 
(SELECT order_no, Shipping_Group,pl_net_price
FROM 
eim-prod.EDW_VIEWS.ORDER_SUBMIT_PRODUCT_LINEITEM 
)
group by 1)
group by 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
You can also tell me if my approach is wrong and how I should take it further as I am a newbie with SQL. Thanks

Divide by zero error when using >, < or <> in Where statement. No division operator involved

I have two CTEs using the same table which holds receipts. Receipt type "a" says how much is billed and may or may not have an amount received. Receipt type "b"s have how much was received if it was received outside of the original receipt. These are matched up by mnth, cusnbr and job. Also on the receipt is how much is allocated for different expenses on the receipt.
I am trying to total up peoples hours if the receipt has been paid at least 99%. These records are based on cusnbr, jobnbr and mnth also. The code below works fine.
with billed as(Select cusnbr
,job
,mnth
,sum(bill_item_1) as 'Billed Item'
,sum(billed) as 'Billed'
From accounting
Where mytype in ('a','b')
Group by cusnbr
,job
,mnth)
paid as(Select cusnbr
,job
,mnth
,sum(rcpt_item_1) as 'Rcpt Item'
,sum(billed) as 'Paid'
From accounting
Where mytype in ('a','b')
Group by cusnbr
,job
,mnth)
Select b.cusnbr
,b.job
,b.mnth
,sum(g.hours) as 'Total Hours'
,b.[Billed Item]
,p.[Rcpt Item]
From billed b inner join paid p
on b.cusnbr = p.cusnbr
and b.job = p.job
and b.mnth = p.mnth
inner join guys g
on b.cusnbr = g.cusnbr
and b.job = g.job
and b.mnth = g.mnth
Where p.[Paid]/b.Billed > .99
The issue I'm having is if I try to add
and b.[Billed Item] <> 0
To the where clause.
I get "Divide by zero error encountered"
I have tried making the last query a CTE with
case when b.[Billed Item] = 0 then 1 else 0 end as flag
and then making another query which checks that flag <> 0
I have tried using isnull(b.[Billed Item],0) in the last query as well as isnull(bill_item_1,0) in the first CTE.
I can get around this issue by dumping the whole thing into a temp table and querying that, but just want to know why this is happening. Using ">","<" or "<>" against b.[Billed Item] results in a divide by zero error.
Use nullif():
Where p.[Paid] / nullif(b.Billed, 0) > 0.99
This will return null -- which does not meet the condition. You can also phrase this more simply without division as:
where p.paid > b.billed * 0.99
I can't answer you question specifically, but I can tell you that SQL does not process all commands if it does not need to. For example,
SELECT COUNT(1/0)
Happily returns 1. So it is quite possible the order of the conditions cause the optimizer to filter out an uncessary division by zero condition.

How to get financials of firms listed at TESA in quantmod?

I'm trying to retrieve financials for firms listed at Tel Aviv Stock Exchange, e.g.: LUMI (Bank Leumi), by quantmod using source=yahoo.
Here is the error I get:
getFin("LUMI",src="yahoo")
Error in thead[x]:thead[x + 1] : NA/NaN argument
I also tried:
getFin("LUMI.TA",src="yahoo")
Error in thead[x]:thead[x + 1] : NA/NaN argument
It seems that getFin does not work for foreign firms, any lead?
First query: Check if the symbol you are searching in Google Finance has financials (as a link/tab) under the Company tab on the left.
getFin/getFinancials is essentially query searching for this through the API configuration.
Also, note that yahoo is overridden by google even after assigning src = "yahoo". Check ?getFin in the console to confirm. It says under the description in help: Download Income Statement, Balance Sheet, and Cash Flow Statements from Google Finance.
If the company's financial statements are not recorded under the U.S. Securities and Exchange Commission, check here: SEC: Enter Company Symbol under Fast Search to see if the European company has filings under the SEC.
For example NVS - Novartis works, unlike LUMI or Nestlé (NSRGY).
library(quantmod)
myData <- new.env()
class(myData)
ls(myData)
NVS <- getFinancials('NVS', env = myData, src = "yahoo", auto.assign=TRUE)
viewFinancials(NVS.f, type= 'IS', period = 'Q') #Options `type=c('BS','IS','CF'), period=c('A','Q')`
Output from: viewFinancials(NVS.f, type= 'IS', period = 'Q') (Truncated output data for view purposes).
> viewFinancials(NVS.f, type= 'IS', period = 'Q')
Quarterly Income Statement for NVS
2014-12-31 2014-09-30 2014-06-30
Revenue 13354.00 13300.00 26980.00
Other Revenue, Total NA NA NA
Total Revenue 13354.00 13300.00 26980.00
Cost of Revenue, Total 4416.00 4421.00 8508.00
Gross Profit 8938.00 8879.00 18472.00
Selling/General/Admin. Expenses, Total 3965.00 3565.00 7463.00
Research & Development 2537.00 2161.00 4388.00
You can get what you need off the BS, IS, or CF by doing the following:
> NVS_Q <- viewFinancials(NVS.f, type= 'IS', period = 'Q')
Quarterly Income Statement for NVS
> Revenue2014_12_31 <- NVS_Q[1,1]
> Revenue2014_12_31
[1] 13354

How to using subquery values in arithmetic operations

My manager wants to see what is total values of our suppliers shipments, and what is the total values of their invoices recorded. So he can see the differencies and want from suppliers to unsended invoices.
Here is my code.
It is working on accounting table and shipment detail table.
fis_meblag0 is always little from zero because it is 320 account so I mutiply it -1 for get real value.
sth_tutar is value of shipment, sth_vergi is VAT and so the sum of them is equal to sum of total with VAT.
Now the hard part.
Manager wants to diference between them in a other column and also sort the valuez z to a.
I know I can reuse same subselect for the getting totals but I want to know that can I achieve this without using the same subquery again.
I mean in first subselect I have the total, in last column I only need just the total, can I use total without compute it again?
Regards
select
ch.cari_kod as Carikod,
ch.cari_unvan1 as Unvani,
(select (sum(mf.fis_meblag0) * -1)
from dbo.MUHASEBE_FISLERI mf
where (mf.fis_tarih > '20141231' and mf.fis_tarih < '20150201')
and mf.fis_hesap_kod = ch.cari_kod
and mf.fis_meblag0 < 0) as mtoplam,
(Select sum (sth.sth_tutar + sth.sth_vergi)
from dbo.STOK_HAREKETLERI sth
where (sth.sth_tarih > '20141231' and sth.sth_tarih < '20150201')
and sth.sth_cari_kodu = ch.cari_kod
and sth.sth_normal_iade = 0
and sth.sth_tip = 0) as stoplam
from
dbo.CARI_HESAPLAR ch
where
ch.cari_kod like '320%'
try this query:
select Carikod, Unvani, mtoplam, stoplam, mtoplam - stoplam as Grand_total
from
(
-- your full query here
) T

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