Jorge Castro DAPT NOV2021
SQL queries Activities
-
Get those accounts that have more transactions than the average.
Answer:
CREATE TEMPORARY TABLE avg_count_trans
SELECT
avg(avg_no_of_transactions_by_account) AS avg_count_trans
FROM
(
SELECT
(
SELECT
avg(count(account_id))
) AS avg_no_of_transactions_by_account
FROM
trans
GROUP BY
account_id
) AS t;
SELECT
account_id,
(
SELECT
floor(avg(count(account_id)))
) AS equal_and_less_than_avg
FROM
trans
GROUP BY
1
HAVING
equal_and_less_than_avg <= (
SELECT
*
FROM
avg_count_trans
)
ORDER BY
2 DESC;
SELECT
account_id,
(
SELECT
floor(avg(count(account_id)))
) AS no_trans_above_avg
FROM
trans
GROUP BY
1
HAVING
no_trans_above_avg > (
SELECT
*
FROM
avg_count_trans
)
ORDER BY
2 DESC;
First I calculate the average number of transactions by account, then calculate the total average which is 192. I have separated the output into accounts with a number of transactions equal or below average and accounts with a number of transactions above average.
If I display only the average number of transactions by account the output would be the averages per account from 6 to 548. This would have been redundant as the second part of the question asked me to display accounts that have more transactions than the average.
Answer:
SELECT
DISTINCT account_id
FROM
account
WHERE
district_id IN (
SELECT
DISTINCT A1
FROM
district
WHERE
A3 = 'central Bohemia'
);
-
Rewrite the previous as a join query.
Answer:
SELECT
account_id,
a3 AS region
FROM
`account` a
INNER JOIN district d ON a.district_id = d.a1
WHERE
a3 = 'central Bohemia';
-
Discuss which method will be more efficient.
Answer:
SELECT
account_id,
count(trans_id) AS num_of_transactions
FROM
trans
WHERE
account_id IN (
SELECT
account_id
FROM
account
WHERE
district_id IN (
SELECT
a1
FROM
district
WHERE
a3 = 'central Bohemia'
)
)
GROUP BY
1
ORDER BY
2 DESC
LIMIT
1;