I have a database of materials that is split into two tables, A and B, each of which contains the name of the material, a property and a reference for the property. Each material can have multiple properties and thus multiple references. I then join the two tables on the name of the material, resulting in a table with on row per material (and a column for each property).
The problem is that I would like to merge all references for a given material into a single, non-repetitive list. Right now I have a column with a group_concat(distinct)
of all references for a material from table A and one column with all references for a material from table B. I can naturally manually concat them references_A || ", " || references_B
but that does not get rid of duplicates.
Below is a minimal example, creating the first table:
CREATE TABLE "attributes" (
"name",
"attribute",
"value",
"reference"
);
INSERT INTO "attributes" VALUES ('DAY', 'Si/Al ratio', '∞', 'XYZ');
INSERT INTO "attributes" VALUES ('NaY', 'Si/Al ratio', '2.4', 'XYZ');
Creating the second table:
CREATE TABLE "properties" (
"name",
"Tmp",
"property",
"value",
"reference"
);
INSERT INTO "properties" VALUES ('DAY', 300, 'capacity', 5.36, 'XYZ');
INSERT INTO "properties" VALUES ('DAY', 320, 'capacity', 7.44, 'XYZ');
INSERT INTO "properties" VALUES ('NaY', 300, 'capacity', 6.8, 'ABC');
INSERT INTO "properties" VALUES ('NaY', 300, 'capacity', 9.4, 'ABC');
And creating the combined view:
CREATE VIEW base AS SELECT
at.name,
pr.Tmp,
max(case when at.attribute = 'Si/Al ratio' then at.value end) `SiAl`,
avg(case when pr.property = 'capacity' then pr.value end) `capacity`,
group_concat(distinct pr.reference) `reference_pr`,
group_concat(distinct at.reference) `reference_at`
FROM attributes at
LEFT JOIN properties pr ON
at.name = pr.name
GROUP BY at.name, pr.Tmp
As to why I start with two tables see my previous question: https://stackoverflow.com/questions/8835443/sqlite-pivot-via-case-how-to-fill-down-a-column