0% found this document useful (0 votes)
19 views4 pages

SQL Interview

Uploaded by

aditya3662
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

SQL Interview

Uploaded by

aditya3662
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 4
SQL Interview Question asked in q > > HsBc Problem Statement Write a SQL query to find the average transaction amount for each account, but only for those accounts where the average transaction amount exceeds the overall average transaction amount across all accounts. Also, include the account name in the result set. Input account_id — transaction_date amount 101 2024-01-01 1000.00 101 2024-01-02 1200.00 102 2024-01-03 800.00 102 2024-01-04 1500.00 103 2024-01-05 2000.00 103 2024-01-06 900.00 Output account_id Avg_amount Table Creation and Data Insertion script ----Table creation Script CREATE TABLE transactions ( account_id INT, transaction_date DATE NOT NULL, amount DECIMAL(10, 2) NOT NULL, ) --Data Insertion Script INSERT INTO transactions (account_id, transaction_date, amount) VALUES (101,'2024-01-01', 1000.00), (101,'2024-01-02', 1200.00), (102,'2024-01-03', 800.00), (102,'2024-01-04', 1500.00), (103,'2024-01-05', 2000.00), (103,'2024-01-06', 900.00) Table Transactions transaction_date amount | 2024-01-01 1000.00 2024-01-02 1200.00 2024-01-03 800.00 2024-01-04 1500.00 2024-01-05 2000.00 2024-01-06 900.00 Solution =select account_id,avg(amount) Avg_amount from transactions t group by account_id having avg(amount)>(select avg(amount) from transactions)| % + Results gil Messages account_id _ Avg_amount 103 | 1450.000000 SQL Script select account_id,avg(amount) Avg_amount from transactions t group by account_id having avg(amount)>(select avg(amount) from transactions) Explanation e First part is to calculate average amount across accounts. Simply using avg() function with grouping by account_id will fetch account wise averge values. © Second part is to figure out overall average value. We can achieve it using avg() function across table. no group by clause needed here. Third part is to compare and find out which accounts are performing better than overall average. We have used having clause against a sub query that returns overall average.

You might also like