I’m trying to create a view that SUMS a table column based on two other columns (id and class), but I’m struggling with the inner query, or at least I think thats the problem.
The VIEW is not recognizing the ‘id’ column and thus is summing the entire column for each id.
I’ve left my attempts out of the fiddle for simplicity and easier understanding.
Here is my sample data...
CREATE TABLE Table1 (id INT,class varchar(10),amount varchar(50));
INSERT INTO Table1 (id,class,amount)
VALUES
(1,'A',.25),
(1,'B',.25),
(1,'B',.25),
(1,'C',.25),
(1,'C',.25),
(1,'C',.25),
(2,'A',.25),
(2,'B',.25),
(2,'B',.25),
(2,'C',.25),
(2,'C',.25),
(2,'C',.25);
...and fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e6aa3d66e791936779ea3a4c5b0d8580
CREATE TABLE Table1 (id INT,class varchar(10),amount varchar(50));
CREATE OR REPLACE VIEW View1 AS
select id,
concat_ws(' / ',
concat_ws('','A:',(select coalesce(SUM(amount),0)
from Table1
where class = 'A')),
concat_ws('','B:',(select coalesce(SUM(amount),0)
from Table1
where class = 'B')),
concat_ws('','C:',(select coalesce(SUM(amount),0)
from Table1
where class = 'C'))
) as totals
from Table1
group by id
The expected outcome for each id should be: A: 0.25 / B: 0.50 / C: 0.75