Re: Help needed creating a view

From: "David Johnston" <polobo(at)yahoo(dot)com>
To: "'Sebastian Tennant'" <sebyte(at)smolny(dot)plus(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Help needed creating a view
Date: 2012-01-26 19:50:45
Message-ID: 001d01ccdc63$cba234e0$62e69ea0$@yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

-----Original Message-----
From: pgsql-general-owner(at)postgresql(dot)org
[mailto:pgsql-general-owner(at)postgresql(dot)org] On Behalf Of Sebastian Tennant
Sent: Thursday, January 26, 2012 6:55 AM
To: pgsql-general(at)postgresql(dot)org
Subject: [GENERAL] Help needed creating a view

Hi list,

Given an 'applications' table for a static set of courses::

user_id (integer)
course_name (text)
completed (boolean)

how best should I go about creating an 'alumni' view with columns:

user_id (integer)
maths (boolean)
english (boolean)
. .
. .
. .

where each of the columns (apart from user_id) is a boolean value
representing whether or not user_id completed each course?

Sebastian
-

----------------------------------------------------------------------------
------------

A) SELECT user_id, CASE WHEN course_name = 'Maths' THEN completed ELSE false
END math_cmp, CASE WHEN course_name = 'English' THEN completed ELSE false
END AS english_cmp .... FROM applications
a) Expand to multiple columns and store either the default "false" or the
value of "completed" into the value for the corresponding column

B) SELECT user_id, CASE WHEN bool_or(math_cmp) THEN true ELSE false END AS
did_math, CASE WHEN bool_or(english_cmp) THEN true ELSE false END AS
did_english FROM "A" GROUP BY user_id
b) Then determine whether the user_id has at least one "true" in the given
column by using the "bool_or" function

Dynamic columns are difficult to code in SQL. You should probably also
include some kind of "OTHER COMPLETED DISCIPLINES" column to catch when you
add an previously unidentified course - "course_name NOT IN
('Maths','English','...')"

Also concerned with the fact that, as coded, a single complete course
triggers the given flag. What happens when you want to specify that they
have only completed 3 of 4 courses? Also, instead of hard-coding the
"course_name" targets you may want to do something like "CASE WHEN
course_name IN (SELECT course_name FROM courses WHERE course_type =
'Maths')".

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Dmitry Koterov 2012-01-26 20:04:55 Stange "duplicate key value violates unique constraint" after "delete" at ON UPDATE trigger
Previous Message Jason Long 2012-01-26 19:24:57 Optimizing Queries Joining Several Views