Sample Header Ad - 728x90

Add column with a sum total to crosstab() query in PostgreSQL 9.0

3 votes
1 answer
6443 views
Following on from my previous question: https://dba.stackexchange.com/questions/114428/creating-crosstab-pivot-table-in-postgresql-9-0 I managed to create a pivot table for ageband using the crosstab() function. I can use this to either create a view or table of the base geometry-less table. However, this still isn't much use as I need to link it to the gazetteers_and_addresses.unit_postcode table in order to assign geometries for further analysis. I will attach the table structure for both tables and the original code that worked to create my crosstab. CREATE OR REPLACE VIEW adult_social_care.vw_ageband AS ( SELECT * FROM crosstab( 'SELECT postcode_nospace_, ageband, count(ageband) as total_count FROM adult_social_care.activities_in_localities_asc GROUP BY postcode_nospace_, ageband ORDER BY postcode_nospace_' ,$$VALUES ('18-24'::text), ('25-34'), ('35-44'), ('45-54'), ('55-64'), ('65-74'), ('75-84'), ('85-94'), ('95 AND OVER')$$) AS ct("postcode" text, "18-24" numeric, "25-34" numeric,"35-44" numeric, "45-54" numeric, "55-64" numeric, "65-74" numeric, "75-84" numeric, "85-94" numeric, "95 AND OVER" numeric)); Table defintions: activities_in_localities_asc: CREATE TABLE adult_social_care.activities_in_localities_asc ( ogc_fid integer NOT NULL, sort numeric(5,0), ageband character(12), postcode_nospace_ character(8), wkb_geometry geometry, CONSTRAINT activities_in_localities_asc_pkey PRIMARY KEY (ogc_fid) ); unit_postcode: CREATE TABLE gazetteers_and_addresses.unit_postcode ( oogc_fid serial NOT NULL, pc_area character(10), postcode_nospaces text, wkb_geometry geometry ); If possible too, assign another field at the end which states a sum of all the fields to give a total_count. If this can be done then I can create dynamic views on different factors using one geometry-less table and unit_postcode.
Asked by daniel franklin (145 rep)
Sep 8, 2015, 02:52 PM
Last activity: Sep 9, 2015, 02:54 AM