Search

Monday, March 7, 2011

SQL Query Questions - Most populer

Query Statement : Having a table "Acct_stat" with column "Trans_type"(Dr or Cr) , "Amount" Pls write a single query which should return sum of "Debit" , "Credit" and "Total Balance" of each account.

Answer : We can use a case statement as best choice for such queries like following with group by Account:

create table Acct_stat (Acount_No varchar2(10),TRANS_TYPE VARCHAR2(2),AMOUNT NUMBER);

insert into Acct_stat values('1' , 'DR' , 100);
insert into Acct_stat values('1' , 'CR' , 100);
insert into Acct_stat values('1' , 'DR' , 100);
insert into Acct_stat values('2' , 'CR' , 100);
insert into Acct_stat values('2' , 'CR' , 100);
insert into Acct_stat values('2' , 'DR' , 100);
insert into Acct_stat values('3' , 'DR' , 100);
insert into Acct_stat values('3' , 'CR' , 100);

SELECT Acount_No ,
SUM (CASE WHEN Trans_type = 'DR'
THEN AMOUNT ELSE null END) DB_SUM,
SUM (CASE WHEN Trans_type = 'CR'
THEN AMOUNT ELSE null END) CR_SUM,
SUM (AMOUNT) TOT_BAL
FROM ACCT_STAT GROUP BY (Acount_No)

No comments:

Post a Comment