I have the following table in a PostgreSQL database:
CREATE TABLE combinaciones
(
id serial NOT NULL,
valor character varying NOT NULL,
CONSTRAINT id_pk PRIMARY KEY (id)
) WITH (OIDS=FALSE);
ALTER TABLE combinaciones OWNER TO postgres;
To which I have inserted the following values:
INSERT INTO combinaciones (valor)
VALUES
('A.1;B.1;F'),
('A.2.1;B.1;F'),
('A.2.1;F'),
('A.3;B.1;F'),
('A.3;B.2;F'),
('A.3;C;D.1;F'),
('A.3;C;F'),
('A.3;D.1;F'),
('A.3;F'),
('B.1;B.2;F');
I need to recover the total of items loaded in all combinations, something like this:
A.1 = 1 veces
A.2.1 = 2 veces
A.3 = 6 veces
B.1 = 4 veces
B.2 = 2 veces
C = 2 veces
D.1 = 2 veces
F = 10 veces
However, when executing the following query:
SELECT
(
CASE
WHEN combinacion LIKE '%A.1%' THEN 'A.1'
WHEN combinacion LIKE '%A.2.1%' THEN 'A.2.1'
WHEN combinacion LIKE '%A.2.2%' THEN 'A.2.2'
WHEN combinacion LIKE '%A.3%' THEN 'A.3'
WHEN combinacion LIKE '%A.4%' THEN 'A.4'
WHEN combinacion LIKE '%B.1%' THEN 'B.1'
WHEN combinacion LIKE '%B.2%' THEN 'B.21'
WHEN combinacion LIKE '%C%' THEN 'C'
WHEN combinacion LIKE '%D.1%' THEN 'D.1'
WHEN combinacion LIKE '%D.2%' THEN 'D.2'
WHEN combinacion LIKE '%D.3%' THEN 'D.3'
WHEN combinacion LIKE '%E.1%' THEN 'E.1'
WHEN combinacion LIKE '%E.2%' THEN 'E.2'
WHEN combinacion LIKE '%E.3%' THEN 'E.3'
WHEN combinacion LIKE '%F%' THEN 'F'
WHEN combinacion LIKE '%G.1%' THEN 'G.1'
WHEN combinacion LIKE '%G.2%' THEN 'G.2'
END
) AS item,
SUM(total) AS total
FROM (
SELECT
valor AS combinacion,
COUNT(valor) AS total
FROM combinaciones
GROUP BY combinacion
ORDER BY 2,1
) AS resultado
GROUP BY item
ORDER BY item;
Return the following:
A.1 = 1 veces
A.2.1 = 2 veces
A.3 = 6 veces
B.1 = 1 veces
Where not only the quantities of some items do not match, but others are also overlooked and do not end up appearing in the final result.
Any suggestions on how to correct the SQL? Thanks from now.
Annex the test of the exercise here: consultation .