If I understood correctly and you want one row per schema, this modified crosstab()
query should work:
SELECT "schema", itemname, "GT", "New", "UnitNo"
FROM public.crosstab($$
SELECT 'c' || itemname, "C_GT_Master" AS sch, itemname
, 'GT'::text AS anal, itemno FROM "C_GT_Master".items
UNION ALL
SELECT 'c' || itemname, "C_GT_Master", itemname
, 'UnitNo', unitno FROM "C_GT_Master".items
UNION ALL
SELECT 'g' || itemname, "G_New_Master", itemname
, 'New' , itemno FROM "G_New_Master".items
UNION ALL
SELECT 'g' || itemname, "G_New_Master", itemname
, 'UnitNo', unitno FROM "G_New_Master".items
ORDER BY 1$$
,$$VALUES ('GT'::text), ('New'), ('UnitNo')$$
)
AS stckreport (
item text, "schema" text, itemname text
, "GT" text, "New" text, "UnitNo" text);
Major points
Add
ORDER BY 1
in the first query string. That was your primary error.I concatenate a hash for the schema to the
itemname
to a value to group by resulting in one row per(schema, itemname)
. In addition I add schema anditemname
separately to have both in the result. Only select those in the outerSELECT
for display. More details about "additional columns":
Pivot on Multiple Columns using Tablefunc
And about concatenating a row name:
crosstab with 2 (or more) row namesUse dollar-quoting to make your life easier.
Use a
VALUES
expression for the second query string.More details in my basic go-to answer for
crosstab()
:
PostgreSQL Crosstab Query