CREATE TABLE sales (
id int auto_increment primary key,
customer VARCHAR(255),
product VARCHAR(255),
sales_quantity INT
);
INSERT INTO sales
(customer, product, sales_quantity)
VALUES
("Customer_A", "Product_01", "100"),
("Customer_B", "Product_03", "970"),
("Customer_B", "Product_04", "730"),
("Customer_C", "Product_02", "480"),
("Customer_D", "Prodcut_01", "320");
Query:
SET
@selected_column = customer;
SELECT
@selected_column
FROM sales_local
GROUP BY 1;
In the query I want to have the flexiblity to change between the columns customer
and product
.
Therefore, my idea was to declare them as variable.
However, with this I get error Unknown column 'customer' in 'field list'
.
Is it possible to declare a column as variable or is there any other similar solution for it?
I know in the simple table above I could achieve this by just changing customer
to product
within the SELECT
part.
However, in my orignal file I use multiple SELECT
statements that are binded with UNION ALL
and I do not want to change the column name in each of those statement.