calculate the balance amount and insert another table - sql

I need some help on building an sql query, I have below two queries, I want to combine the sum of debit substracted from credit and then insert result as balance into another table
select sum(amount)
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='credit' and account_type='customer' and IS_DELETED='false'
select sum(amount)
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='debit' and account_type='customer' and IS_DELETED='false'

Could use CROSS APPLY
select a.*, b.CreditSum, c.DebitSum
from ACCOUNT_TRANSACTIONS a
cross apply
(select sum(amount) as CreditSum
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='credit' and account_type='customer' and IS_DELETED='false'
) b
cross apply
(select sum(amount) as DebitSum
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='debit' and account_type='customer' and IS_DELETED='false'
) c
where a.CUSTOMER_USER_NAME='55555' and a.account_type='customer' and a.IS_DELETED='false'

You can do this using conditional aggregation:
select sum(case when transaction_type = 'credit' then amount when transaction_type = 'debit' then - amount end) as balance
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME = '55555' and
account_type = 'customer' and
IS_DELETED = 'false' ;
You would then insert this into another table using insert, although I'm not sure how a single value in a single row would be useful.

Related

Using SQL result as a filter for another query

Here's my code and there's a thousand transaction_no result. Which is I have to use as a filter for another code with the same table.
select Item_Code, Transaction_No, Sales, Quantity
from `transaction_table`
where item_code = 'HTHP-P'
You could use in, if you want to filter on the transactions:
select . . .
from `transaction_table` tt
where tt.transacton_no in (select tt2.Transaction_No
from `transaction_table` tt2
where tt2.item_code = 'HTHP-P'
);
If you want all rows for transactions that have the specified item, you can also use qualify:
select tt.*
from `transaction_table` tt
where 1=1
qualify countif(tt2.item_code = 'HTHP-P') over (partition by Transaction_No) > 0;
You could use 'in' to filter using the results.
select Item_Code, Transaction_No, Sales, Quantity
from `transaction_table`
where Transaction_No in ( select t.Transaction_No from `transaction_table` t where t.item_code = 'HTHP-P')
or You could store all the results in a temp table and then use the results to filter later in another section of the code.
create table #temp
(
Transaction_No varchar(30)
);
insert into #temp
select Transaction_No from `Tranaction_Table` where item_code = 'HTHP-P'

How do I find the account having the maximum balance in each branch of a bank using SQL?

How do I find the account having the maximum balance in each branch of a bank using SQL? I have a table having 3 columns account number, balance and branch.
If you are using SQL server the following will work using ROW_NUMBER():
CREATE TABLE #TEMP_A
(
BALANCE INT,
BRANCH VARCHAR(20),
ACCOUNT INT
)
INSERT INTO #TEMP_A
VALUES(100,'WEST',001)
INSERT INTO #TEMP_A
VALUES(200,'WEST',002)
INSERT INTO #TEMP_A
VALUES(400,'EAST',003)
INSERT INTO #TEMP_A
VALUES(500,'EAST',004)
SELECT ACCOUNT FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY BRANCH ORDER BY BALANCE DESC) AS ROWNUM,* FROM #TEMP_A
) AS X WHERE ROWNUM = 1
---------+---------+---------+---------+---------+---------+---------+
SELECT DISTINCT(A.ACCOUNT), TMP.BRANCH, TMP.AMT
FROM TABLE A,
( SELECT BRANCH, MAX(AMOUNT) AS AMT
FROM TABLE
GROUP BY BRANCH) AS TMP
WHERE A.BRANCH = TMP.BRANCH
AND A.AMOUNT = TMP.AMT
GROUP BY A.ACCOUNT, TMP.BRANCH, TMP.AMT ;
---------+---------+---------+---------+---------+---------+---------+

GROUP BY after CASE WHEN

I am trying to create a table from a join and summing some fields based on id. This part is working great. I am also trying to add an additional column and using a case when statement I want to populate it.
Here is the script
CREATE TABLE TABLE1
AS
SELECT ID, IDC, SUM(AMOUNT) PRICE, SUM(COST) COST, SUM(AMOUNT-COST) PROFIT,
CASE PROFIT
WHEN PROFIT < 1000 THEN 'Low'
WHEN PROFIT < 5000 THEN 'Medium'
ELSE 'High'
END AS PROFITLEVEL
FROM
(SELECT DISTINCT ID, IDC, AMOUNT, COST
FROM ORDER_ITEMS
LEFT JOIN ORDERS
ON ID = IDC)
GROUP BY ID, IDC;
This however returns a ORA-00905 : Missing keyword error.
Any help would be appreciated
You are using the CASE in a wrong way; besides, you try to use the alias PROFIT at the same level you define it.
You need to edit you CASE and use the expression that gives the PROFIT instead of the alias PROFIT:
CREATE TABLE TABLE1 AS
SELECT ID,
IDC,
SUM(AMOUNT) PRICE,
SUM(COST) COST,
SUM(AMOUNT - COST) PROFIT,
CASE
WHEN SUM(AMOUNT - COST) < 1000 THEN 'Low'
WHEN SUM(AMOUNT - COST) < 5000 THEN 'Medium'
ELSE 'High'
END AS PROFITLEVEL
FROM (SELECT DISTINCT ID,
IDC,
AMOUNT,
COST
FROM ORDER_ITEMS LEFT JOIN ORDERS ON ID = IDC)
GROUP BY ID, IDC;
The way you tried to use the CASE is useful if you need to check single values; for example:
select level,
case level
when 1 then 'one'
when 2 then 'two'
else 'other'
end
from dual
connect by level <=3

How to query specific values for some columns and sum of values in others SQL

I'm trying to query some data from SQL such that it sums some columns, gets the max of another column and the corresponding row for a third column. For example,
|dataset|
|shares| |date| |price|
100 05/13/16 20.4
200 05/15/16 21.2
300 06/12/16 19.3
400 02/22/16 20.0
I want my output to be:
|shares| |date| |price|
1000 06/12/16 19.3
The shares have been summed up, the date is max(date), and the price is the price at max(date).
So far, I have:
select sum(shares), max(date), max(price)
but that gives me an incorrect price.
EDIT:
I realize I was unclear in my OP, all the other relevant data is in one table, and the price is in other. My full code is:
select id, stock, side, exchange, max(startdate), max(enddate),
sum(shares), sum(execution_price*shares)/sum(shares), max(limitprice), max(price)
from table1 t1
INNER JOIN table2 t2 on t2.id = t1.id
where location = 'CHICAGO' and startdate > '1/1/2016' and order_type = 'limit'
group by id, stock, side, exchange
You can do this with window functions and aggregation. Here is an example:
select sum(shared), max(date), max(case when seqnum = 1 then price end) as price
from (select t.*, row_number() over (order by date desc) as seqnum
from t
) t;
EDIT:
If the results that you are looking at are in fact the result of a query, you can do:
with t as (<your query here>)
select sum(shared), max(date), max(case when seqnum = 1 then price end) as price
from (select t.*, row_number() over (order by date desc) as seqnum
from t
) t;
Heres one way to do it .... the join would obviously include the ticker symbol for the share also
select
a.sum_share,
a.max_date
b.price
FROM
(
select ticker , sum(shares) sum_share, max(date) max_date from table where ticker = 'MSFT' group by ticker
) a
inner join table on a.max_date = b.date and a.ticker = b.ticker

SQL Server correlated query want to take sum

select
SUM(Convert(int, (Select SUM(Convert(int, amount))
from ChargesType
where ChargesType.ID = Charges.ChargesTypeID))) as Amount
from Charges
Where Charges.RollNo = 1
This is my query; I want to get sum of amount column.
Try this instead:
select
SUM(t.Amount) as Amount
from Charges AS c
INNER JOIN
(
SELECT Convert(int, amount) AS Amount, ID
FROM ChargesType
) AS t ON t.ID = c.ChargesTypeID
Where c.RollNo = 1