java financial year wise sum Of Amount - sql

I am stuck with a query to fetch sum of transaction amount financial year wise.
My table is
TXN_DATE TXN_AMOUNT
12/01/2014 100
12/08/2014 200
12/01/2015 300
12/04/2015 400
12/04/2013 500
I want the result to be displayed as
FinYear Amount
2013-2014 600
2014-2015 500
2015-2016 400
Considering financial year duration from 1st April of an year to 31st March of next year.
Databse DB2
Date is timestamp in database and date format specified in the example is dd/MM/yyyy

Following query should do (tested in DB2 LUW):
with temp as (finyear, txn_amount) as (
select case
when month(TXN_DATE)< 4 Then year(TXN_DATE)-1 || '-' || year(TXN_DATE)
else month(TXN_DATE)>= 4 Then year(TXN_DATE) || '-' || year(TXN_DATE)+1
end as finyear,
txn_amount
from test4)
select finyear,
sum(txn_amount) as sum_amount
from temp
group by finyear;

SELECT FinYear, cast(sum(Amount) as decimal(16,2)) AS Amount FROM
(SELECT
CASE
WHEN TXN_DATE > to_date(year(TXN_DATE) ||'-03-31','YYYY/MM/DD') THEN CONCAT(CONCAT(year(TXN_DATE),'-'),year(TXN_DATE)+1)
WHEN TXN_DATE < to_date(year(TXN_DATE) ||'-04-01','YYYY/MM/DD') THEN CONCAT(CONCAT(year(TXN_DATE)-1,'-'),year(TXN_DATE))
END as FinYear,
Amount AS Amount
FROM tab1)
GROUP BY FinYear

You can use following query:
SELECT FinYear, sum(Amount) AS Amount FROM
(SELECT FinYear =
CASE
WHEN TXN_DATE > char(year(TXN_DATE)) +'0331' THEN char(year(TXN_DATE))+'-'+char(year(TXN_DATE)+1)
WHEN TXN_DATE < char(year(TXN_DATE)) +'0401' THEN char(year(TXN_DATE)-1)+'-'+char(year(TXN_DATE))
END,
TXN_AMOUNT AS Amount
FROM DB2.Transactions) AS Table1
GROUP BY FinYear
Make sure you replace DB2.Transactions with your DatabaseName.TableName

Related

SQL Divide previous row balance by current row balance and insert that value into current rows column "Growth"

I have a table where like this.
Year
ProcessDate
Month
Balance
RowNum
Calculation
2022
20220430
4
22855547
1
2022
20220330
3
22644455
2
2022
20220230
2
22588666
3
2022
20220130
1
33545444
4
2022
20221230
12
22466666
5
I need to take the previous row of each column and divide that amount by the current row.
Ex: Row 1 calculation should = Row 2 Balance / Row 1 Balance (22644455/22855547 = .99% )
Row 2 calculation should = Row 3 Balance / Row 2 Balance etc....
Table is just a Temporary table I created titled #MonthlyLoanBalance2.
Now I just need to take it a step further.
Let me know what and how you would go about doing this.
Thank you in advance!
Insert into #MonthlytLoanBalance2 (
Year
,ProcessDate
,Month
,Balance
,RowNum
)
select
--CloseYearMonth,
left(ProcessDate,4) as 'Year',
ProcessDate,
--x.LOANTypeKey,
SUBSTRING(CAST(x.ProcessDate as varchar(38)),5,2) as 'Month',
sum(x.currentBalance) as Balance
,ROW_NUMBER()over (order by ProcessDate desc) as RowNum
from
(
select
distinct LoanServiceKey,
LoanTypeKey,
AccountNumber,
CurrentBalance,
OpenDateKey,
CloseDateKey,
ProcessDate
from
cu.LAFactLoanSnapShot
where LoanStatus = 'Open'
and LoanTypeKey = 0
and ProcessDate in (select DateKey from dimDate
where IsLastDayOfMonth = 'Y'
and DateKey > convert(varchar, getdate()-4000, 112)
)
) x
group by ProcessDate
order by ProcessDate desc;``
I am assuming your data is already prepared as shown in the table. Now you can try Lead() function to resolve your issue. Remember format() function is used for taking only two precision.
SELECT *,
FORMAT((ISNULL(LEAD(Balance,1) OVER (ORDER BY RowNum), 1)/Balance),'N2') Calculation
FROM #MonthlytLoanBalance2

Extracting account's transactions with no other transactions with this counterparty

I have a database with transactions of accounts. The relevant columns for me are: Account,Amount, Date, description and Transaction_Code.
My goal is to extract rows for a given account which meets my trigger points.
The trigger points which I've succeeded writing are Amount greater than 200 and Transaction_Code in ('1,'2','3').
the only trigger point I'm struggling with is that: The account has no other transactions with this counterparty in the last 21 days. I've only succeeded in taking the range of dates I need.
Example for the Dataset:
**Account** **Amount** **Date** **Description** **Transaction_Code**
555 280 2019-10-06 amt_fee 1
555 700 2019-09-20 refund 2
555 250 2019-10-01 amt_fee 1
snippet of sql I wrote for the example for better understanding:
select Account, Amount, Date, Description
from MyTable
where Account = '555' and Date between '2019-09-15' and '2019-10-06'
and Amount >= 200
and Transaction_Code in ('1','2','3')
The problem I have is how to do the condition of: ''The account has no other transactions with this counterparty in the last 21 days.'' Counterparty refers to the Description or Transaction_Code columns.
How should I do that condition for my true larger dataset? with groupby and count distinct?
You could add a not exists condition with a correlated subquery that ensures that the same Account did not have a transaction with the same Description or Transaction_Code within the last 21 days.
select Account, Amount, Date, Description
from MyTable t
where
Account = '555' and Date between '2019-09-15' and '2019-10-06'
and Amount >= 200
and Transaction_Code in (1, 2, 3)
and not exists (
select 1
from MyTable t1
where
t1.Account = t.Account
and (t1.Description = t.Description or t1.Transaction_Code = t.Transaction_Code)
and t1.date < t.date
and t1.date >= dateadd(day, -21, t.date)
)

Oracle/SQL -Sales broken out by Months

Hello I have created the following query to pull total order by month for a salesMen. while this gets me the data I need for a single salesmen i need to run this for more than just one. what I would like to accomplish is a query that pull for several different salesmen and is broken out by month and the Months being the Columns names(Columns dynamic to months being pulled). Like below.
SalesMen - 10-2017 - 11-2017 - 12-2017 - 01/2018
------------------------------------------------------------
Salesmen_1 Month_total(5) 15 300 100
Salesmen_2 100 948 821 684
Current Code:
select (case when region_code in ('123','124') then 'SalesMen_1' else 'N/A' end)SalesMen, to_char(DATE_ENTERED, 'MM-YYYY') as MM_YYYY, Count(ORder_NO) as Month_Total
from ORDERS
where
REGEXP_like (ORder_NO, '^W|^E')
and DATE_ENTERED between ADD_MONTHS(TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, 2), 'YYYY') || '-01-01', 'YYYY-MM-DD'), -3) and TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM')|| '-01', 'YYYY-MM-DD') - 1
and region_code in ('123','124')
group by to_char(DATE_ENTERED, 'MM-YYYY'),(case when region_code in ('123','124') then 'SalesMen_1' else 'N/A' end)
order by to_char(DATE_ENTERED, 'MM-YYYY') desc
Results:
Current Results Example

Grouping multiple selects within a SQL query

I have a table Supplier with two columns, TotalStock and Date. I'm trying to write a single query that will give me stock totals by week / month / year for a list of suppliers.
So results will look like this..
SUPPLIER WEEK MONTH YEAR
SupplierA 50 100 2000
SupplierB 60 150 2500
SupplierC 15 25 200
So far I've been playing around with multiple selects but I can't get any further than this:
SELECT Supplier,
(
SELECT Sum(TotalStock)
FROM StockBreakdown
WHERE Date >= '2014-5-12'
GROUP BY Supplier
) AS StockThisWeek,
(
SELECT Sum(TotalStock)
FROM StockBreakdown
WHERE Date >= '2014-5-1'
GROUP BY Supplier
) AS StockThisMonth,
(
SELECT Sum(TotalStock)
FROM StockBreakdown
WHERE Date >= '2014-1-1'
GROUP BY Supplier
) AS StockThisYear
This query throws an error as each individual grouping returns multiple results. I feel that I'm close to the solution but can't work out where to go
You don't have to use subqueries to achieve what you want :
SELECT Supplier
, SUM(CASE WHEN Date >= CAST('2014-05-12' as DATE) THEN TotalStock END) AS StockThisWeek
, SUM(CASE WHEN Date >= CAST('2014-05-01' as DATE) THEN TotalStock END) AS StockThisMonth
, SUM(CASE WHEN Date >= CAST('2014-01-01' as DATE) THEN TotalStock END) AS StockThisYear
FROM StockBreakdown
GROUP BY Supplier
You may need to make the selects for the columns return only a single result. You could try this (not tested currently):
SELECT Supplier,
(
SELECT TOP 1 StockThisWeek FROM
(
SELECT Supplier, Sum(TotalStock) AS StockThisWeek
FROM StockBreakdown
WHERE Date >= '2014-5-12'
GROUP BY Supplier
) tmp1
WHERE tmp1.Supplier = Supplier
) AS StockThisWeek,
(
SELECT TOP 1 StockThisMonth FROM
(
SELECT Supplier, Sum(TotalStock) AS StockThisMonth
FROM StockBreakdown
WHERE Date >= '2014-5-1'
GROUP BY Supplier
) tmp2
WHERE tmp2.Supplier = Supplier
) AS StockThisMonth,
...
This selects the supplier and then tries to create two columns StockThisWeek and StockThisMonth by selecting the first entry from the select you created before. As through the GROUP BY there should only be one entry per supplier, so you don't lose and data.

Join two Queries so that the second query becomes a row in the results of query 1

I have two queries that I would like to combine so i can make a chart out of the results.
The results have to be very specific or the chart will not display the information properly
I am using MS SQL in Crystal Reports 11
Below is the results I am looking for.
Date Invoice Type Amount
2012/08 Customer Payment 500
2012/08 Customer Invoice 1000
2012/08 Moving Balance 1500
2012/09 Customer Invoice 400
2012/09 Moving Balance 1900
2012/10 Interest 50
2012/10 Moving Balance 1950
So the First query returns the following results
Date Invoice Type Amount
2012/08 Customer Payment 500
2012/08 Customer Invoice 1000
2012/09 Customer Invoice 400
2012/10 Interest 50
and the second query returns
Date Invoice Type Amount
2012/08 Moving Balance 1500
2012/09 Moving Balance 1900
2012/10 Moving Balance 1950
The second query is very long and complicated with a join .
What is the best way of joining these two queries
so that I have one column called invoice Type ( as the chart is based on this field)
that covers all the invoice types plus the moving balance
I assume that the place of the Moving Balance rows inside the result set is important.
You can do something like this:
select date, invoice_type, amount
from
(
select date, invoice_type, amount from query1
union all
select date, invoice_type, amount from query2
)
order by date, case invoice_type when 'Moving Balance' then 1 else 0 end
This first appends the results of the second query to the results of the first query and then reorders the resulting list first by date and then by the invoice type in such a way that the row with Moving balance will come last.
With the actual queries you have given, it should look something like this:
select date, invoice_type, amount
from
(
SELECT
CONVERT(VARCHAR(7),case_createddate, 111) AS Date,
case_invoicetype as invoice_type,
Sum(case_totalexvat) as amount
FROM cases AS ca
WHERE case_primaryCompanyid = 2174 and
datediff(m,case_createddate,getDate())
union all
select
CONVERT(VARCHAR(7),ca.case_createddate, 111) AS Date,
'Moving Balance' as Invoice_Type,
sum(mb.Amount) as Amount
from
cases as ca
left join (
select
case_primaryCompanyId as ID,
case_createdDate,
case_TotalExVat as Amount
from
cases
) mb
on ca. case_primaryCompanyId = mb.ID
and ca.case_createdDate >= mb.case_CreatedDate
where
ca.case_primaryCompanyId = 2174 and
ca.case_createdDate > DATEADD(m, -12, current_timestamp)
group by
case_primaryCompanyId,
CONVERT(VARCHAR(7),ca.case_createddate, 111)
order by ca.case_primaryCompanyid, CONVERT(VARCHAR(7),ca.case_createddate, 111)
)
order by date, case invoice_type when 'Moving Balance' then 1 else 0 end
You can use Union and can use Order by clause
Select * from (Query 1
Union
Query 2
) as a Order by a.Date Asc