SQL - Running of SP sums the first row as NULL - sql

I'm trying to develop a SP for Transaction operation , The SP gets as parameters the Username of the player , The Transaction amount, and the Type of the Transaction if it's Deposit / Draw .
My problem is when the first row enters to the table my TotalAmount column in the tables the sums the total amount by Username starts from NULL for each username instead of the first deposit .
From the second row to the same username it's sums the total amount fine .
The SP -
https://i.stack.imgur.com/8RmW2.png
The Problem -
https://i.stack.imgur.com/NYTSx.png
Thanks!

You have code like this :
SET #TotalAMT = (#TransactionAMT + ( ... some code here))
Change it like this
SET #TotalAMT = (#TransactionAMT + COALESCE( ... some code here), 0)

Related

Problems with sql query return

Friends, good afternoon! I have the following problem, I use the oracle developed database, and I have a procedure, in a part of this procedure I perform a validation that returns a repeated person's name and write a log to the user informing what happened.
However, at the user's request, he asked me to add a new field to this log called pgtoVlrBruto = which means gross payment amount. I have a table called procInter, but I can't make a code that I can adapt within the query, I have no idea how I would get this field. Could someone guide me please?
controlExec: = 'GENERATE LOG MESSAGE - 1.';
IF codProcess IS NOT NULL and codProcess <> 0 THEN
qtdExists: = 0;
BEGIN
SELECT COUNT (*)
INTO qty
FROM (SELECT PI.COD_INTER, PI.PGVLRGROSS FROM PROC_INTER PI
INNER JOIN PROCESS P ON P.COD_PROCESS = PI.COD_PROCESS
WHERE P.COD_PROCESS = codProcess) TB
WHERE TB.COD_INTER = codInterested (Variable assigned at the beginning of the procedure.);
EXCEPTION
WHEN NO_DATA_FOUND THEN
qtdExists: = 0;
END;
IF qtyExists> 0 THEN
--Part of the query that I programmed that would help me, but I can't adapt it in the query above the procedure.
--SELECT PI.PGVLRBRUTO
--INTO pgVlrGROSS
--FROM PROC_INTER PI
--WHERE PI.cod_process = codprocess
--and PI.COD_INTERESSADO = codInterested
--and pi.cod_sep = SEP;

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.

Populate rows based on another row ( Copy Prices from branch 0, to all other branches)

I am trying to populate rows based on another row,
For example
Update the Product Price table where branchID = 0
to all other products where the branchid <> 0 based on each product code
In the table there is
7 rows of the same product, each row is meant to be identical, but the only difference is the branchid
I want all data from branch 0 row to populate the rest for the product
my current update script does run, but it uses up so much space on the transaction log that it fails, and it takes 2 hours to run
UPDATE ProductPrice
SET StandardSell = pp2.StandardSell,
StandardBuy = pp2.StandardBuy,
InternalCost = pp2.InternalCost,
BuyPerID = pp2.BuyPerID,
AverageCostPerID = pp2.AverageCostPerID,
InternalCostPerID = pp2.InternalCostPerID,
SellPerID = pp2.SellPerID
FROM (SELECT BranchID, ProductID, StandardSell, StandardBuy,SellPerID, InternalCost,BuyPerID,AverageCostPerID,InternalCostPerID
FROM ProductPrice
WHERE BranchID = 0
) AS pp2 INNER JOIN
ProductPrice AS pp1
on pp1.ProductID = pp2.ProductID
WHERE pp1.ProductID = pp2.ProductID
I want products to be updated with the prices from branch 0 to all other branches per product.
This is too long for a comment.
The first observation is that you should fix your data model. Repeating the same columns on seven records is evidence that your data is not normalized. The seven columns that you want to update should probably be in the ProductPrice table.
Then you want a ProductBranch table, with additional columns and the branch id.
That said, if you are stuck with the data model, you are stuck with an update that basically updates all rows. Instead, create a new table with all the columns you want:
insert into temp_productprice
select . . .
from . . .;
Then truncate productprice and insert the new data into it. A bulk insert is more efficient than a giant update.
Finally, you could also try using window functions:
with toupdate as (
select pp.*,
max(case when branchid = 0 then StandardSell end) as StandardSell_0,
max(case when branchid = 0 then StandardBuy end) as StandardBuy_0,
from productprice pp
. . .
)
update toupdate
set StandardSell = StandardSell_0,
StandardBuy = StandardBuy_0,
. . .
from branchid <> 0;
Thank you for your suggestions,
In the end I just gave the log file more space. Then let it run- it takes 2 hours though lol.
But its done
Thanks the script i posted works for anyone elses use.

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

Querying the number of specific items in a database

I was just wondering how could I count the number of a specific equipment..
SELECT
EQUIPMENTS.DESCRIPTION AS [EQUIPMENT TYPE],
Count(EQUIPMENTS.EQNAME) AS QUANTITY,
(SELECT Count(EQUIPMENTS.CONDITION) FROM EQUIPMENTS WHERE EQUIPMENTS.CONDITION = 'Functional') AS WORKING,
(SELECT Count(EQUIPMENTS.CONDITION) FROM EQUIPMENTS WHERE EQUIPMENTS.CONDITION = 'Non-Functional') AS [NON-WORKING]
FROM EQUIPMENTS
GROUP BY EQUIPMENTS.DESCRIPTION;
this query returns the following :
EQUIPMENT NAME : PROJECTOR
QUANTITY : 3
WORKING : 2
NON-WORKING :1
Now if I add another equipment which has a different type, for example CALCULATOR, it would have the same count of WORKING AND NON-WORKING which only is for the PROJECTOR. How do I Make it such that it also counts the quantity of the Calculator and the number of working and non-working itself? I mean whenever I add another equipment which has a specific description, the query would also count it independently?
I'm using VB.NET and this query is made in MS ACCESS 2007.
Use IIf() expressions to return 1 when the condition is satisfied, and 0 when not. Then Sum those values.
SELECT
e.DESCRIPTION AS [EQUIPMENT TYPE],
Count(e.EQNAME) AS QUANTITY,
Sum(IIf(e.CONDITION = 'Functional', 1, 0)) AS WORKING,
Sum(IIf(e.CONDITION = 'Non-Functional', 1, 0)) AS [NON-WORKING]
FROM EQUIPMENTS AS e
GROUP BY e.DESCRIPTION;