I'm attempting to return any day with total transactions exceeding the average:
WITH avg_daily_transaction AS
(
SELECT created_at, SUM(amount) daily_transactions
FROM transactions
GROUP BY created_at
)
SELECT D.created_at, D.daily_transactions, D.avg_transaction
FROM
(
SELECT created_at, daily_transactions, ROUND(AVG(daily_transactions) OVER (), 0) avg_transaction
FROM avg_daily_transaction
) D
WHERE D.daily_transactions > D.avg_transaction;
The table is setup as:
CREATE TABLE transactions (
id INT AUTO_INCREMENT,
created_at DATE NOT NULL,
posted_at DATE NOT NULL,
transactions VARCHAR(255) NOT NULL,
category VARCHAR(255) NOT NULL,
sub_category VARCHAR(255)
DEFAULT '',
amount INT NOT NULL,
alert VARCHAR(255)
DEFAULT '',
PRIMARY KEY (id)
);
However, the avg component does not seem to be working properly, as the average for all days is -60.45:
How can I tweak the query to return the correct average value? Also, apologies for using an image here, if someone has an alternative method for sharing table results from MySQL please let me know!
EDIT (09/19): See below for sample data:
INSERT INTO transactions (created_at, posted_at, transactions, category, sub_category, amount, alert)
VALUES ('2022-08-24', '2022-08-24', 'A', 'dining', 'leisure', -10, ''),
('2022-08-24', '2022-08-24', 'A1', 'dining', 'daily', -30, ''),
('2022-08-24', '2022-08-24', 'B2', 'shopping', 'leisure', -60, ''),
('2022-08-25', '2022-08-25', 'B1', 'groceries', '', -90, ''),
('2022-08-26', '2022-08-26', 'B6', 'shopping', 'home', -100, '');
The desired outcome is to return the created_at, and sum(amount) for all days that have total transactions greater than the average daily total transactions. In the case of the sample data 2022-08-24 and 2022-08-26 both total -100, which exceeds the average of -96, and should be returned.
