pg.ddx.io pgsql-general@postgresql.org mailing list archive
help / color / mirror / Atom feedQuery help...
70+ messages / 45 participants
[nested] [flat]
* Query help...
@ 2001-08-11 11:04 Joshua Adam Ginsberg <rainman@owlnet.rice.edu>
0 siblings, 2 replies; 70+ messages in thread
From: Joshua Adam Ginsberg @ 2001-08-11 11:04 UTC (permalink / raw)
To: pgsql-general
A simplified version of my situation...
I've got three tables that I'm working with... the first is a table of
staff members... firstname, lastname, staffid... nothing tough... the
second is a table of jobs... job title, jobid... nothing tough... the
third is a history of job assignments... it's got a staffid, a jobid, a
timestamp, and a field to denote whether the job was added or dropped...
this third table exists because it is useful in this project to be able
to look at a staff member's job history...
The problem I'm running into is queries that attempt to determine who is
an "active" member of the staff, defined as a staff member who currently
has at least one job added but not dropped... this can be easily
measured by saying that if the number of times a staff member had a job
added is greater than the number of times that same staff member had a
job dropped, that staff member is active...
What I'm having trouble figuring out is how can I incorporate those
rowcounts into a greater query...
I've succeeded in some other cases... I can get a list of the active
personnel:
select staff.staff_id, firstnames, lastname, jobs.job_id, job_title from
staff, staff_history, jobs where staff.staff_id = staff+history.staff_id
and jobs.job_id = staff_history.job_id group by staff.staff_id,
firstnames, lastname, jobs.job_id, job_title having (count(add_or_drop)
% 2) = 1 order by lastname, firstnames;
This succeeds because for each person-job combination, if there's 0 mod
2 instances of them, then the person has added and dropped the job (some
number of times)... if there's 1 mod 2 instances, then the person has
added but not dropped the job...
I can get a list of jobs and who is actively assigned to the job:
select jobs.job_id, job_title, staff.staff_id, firstnames, lastname from
jobs left outer join (staff_history join staff on
(staff_history.staff_id = staff.staff_id)) on (jobs.job_id =
staff_history.job_id) group by jobs.job_id, staff.staff_id, job_title,
firstnames, lastname having (count(staff.staff_id) % 2 = 1);
This succeeds because for each grouping, which again is a person-job
combination, I can eliminate anybody who has been assigned and
deassigned to the same job the same number of times...
But here's a case where I can't figure it out... I'm trying to generate
a list of staff members with the "active" staff members first... now, I
can't use my same of mod 2 here, because a person can have more than one
job... so if i have been added to two jobs but not removed from any,
count(add_or_drop) % 2 = 0, but I am active...
Any suggestions?
-jag
--
--------------------------------------------------------
Joshua Ginsberg rainman@owlnet.rice.edu
Director of Technology dirtech@sa.rice.edu
Student Association AIM: L0stInTheDesert
Rice University, Houston, TX
========================================================
"Programming today is a race between software engineers
striving to build bigger and better idiot-proof programs
and the Universe trying to produce bigger and better
idiots. So far, the Universe is winning." -Rich Cook
--------------------------------------------------------
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help...
@ 2001-08-11 16:50 Thomas Lockhart <lockhart@fourpalms.org>
parent: Joshua Adam Ginsberg <rainman@owlnet.rice.edu>
1 sibling, 2 replies; 70+ messages in thread
From: Thomas Lockhart @ 2001-08-11 16:50 UTC (permalink / raw)
To: Joshua Adam Ginsberg <rainman@owlnet.rice.edu>; +Cc: pgsql-general
> I've got three tables that I'm working with... the first is a table of
> staff members... firstname, lastname, staffid... nothing tough... the
> second is a table of jobs... job title, jobid... nothing tough... the
> third is a history of job assignments... it's got a staffid, a jobid, a
> timestamp, and a field to denote whether the job was added or dropped...
> this third table exists because it is useful in this project to be able
> to look at a staff member's job history...
...
> Any suggestions?
Perhaps not a helpful one... but I would be inclined to reorganize that
third table to have a "start date" *and* a "stop date" field, and ditch
the "dropped" boolean:
o it would keep you from having to figure out how to associate two
entries in the same table with the same job (the added and dropped
rows). How would you currently prevent a job from being entered as
"dropped" without a corresponding "added" row?
o it would make it easier to do the query you are asking about; to tell
whether someone has an active job, just select on a date -- like 'today'
-- between the start and stop dates.
o it may better match reality; jobs have a duration so represent that
explicitly.
hth
- Thomas
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help...
@ 2001-08-11 16:59 Andrew Gould <andrewgould@yahoo.com>
parent: Joshua Adam Ginsberg <rainman@owlnet.rice.edu>
1 sibling, 0 replies; 70+ messages in thread
From: Andrew Gould @ 2001-08-11 16:59 UTC (permalink / raw)
To: Joshua Adam Ginsberg <rainman@owlnet.rice.edu>; pgsql-general
Have you thought about adding an integer field (we'll
call it 'status')that is dependent upon the
add_or_drop filed? (I'm assuming that add_or_drop has
a not null constraint and must have either 'add' or
'drop'.)
Before running report queries run:
update staff_history
set add_drop_status = case when add_or_drop='add' then
1 else -1 end;
The following query should give you a list of active
staff/job combinations:
select staff_id, job_id, max(date_filed) as eff_date,
sum(add_drop_status) as status from staff_history
group by staffid, job_id having sum(add_drop_status) >
0;
Of course, if you just change add_or_drop to the
status field, you can eliminate the update step.
I hope this helps.
Andrew Gould
--- Joshua Adam Ginsberg <rainman@owlnet.rice.edu>
wrote:
> A simplified version of my situation...
>
> I've got three tables that I'm working with... the
> first is a table of
> staff members... firstname, lastname, staffid...
> nothing tough... the
> second is a table of jobs... job title, jobid...
> nothing tough... the
> third is a history of job assignments... it's got a
> staffid, a jobid, a
> timestamp, and a field to denote whether the job was
> added or dropped...
> this third table exists because it is useful in this
> project to be able
> to look at a staff member's job history...
>
> The problem I'm running into is queries that attempt
> to determine who is
> an "active" member of the staff, defined as a staff
> member who currently
> has at least one job added but not dropped... this
> can be easily
> measured by saying that if the number of times a
> staff member had a job
> added is greater than the number of times that same
> staff member had a
> job dropped, that staff member is active...
>
> What I'm having trouble figuring out is how can I
> incorporate those
> rowcounts into a greater query...
>
> I've succeeded in some other cases... I can get a
> list of the active
> personnel:
>
> select staff.staff_id, firstnames, lastname,
> jobs.job_id, job_title from
> staff, staff_history, jobs where staff.staff_id =
> staff+history.staff_id
> and jobs.job_id = staff_history.job_id group by
> staff.staff_id,
> firstnames, lastname, jobs.job_id, job_title having
> (count(add_or_drop)
> % 2) = 1 order by lastname, firstnames;
>
> This succeeds because for each person-job
> combination, if there's 0 mod
> 2 instances of them, then the person has added and
> dropped the job (some
> number of times)... if there's 1 mod 2 instances,
> then the person has
> added but not dropped the job...
>
> I can get a list of jobs and who is actively
> assigned to the job:
>
> select jobs.job_id, job_title, staff.staff_id,
> firstnames, lastname from
> jobs left outer join (staff_history join staff on
> (staff_history.staff_id = staff.staff_id)) on
> (jobs.job_id =
> staff_history.job_id) group by jobs.job_id,
> staff.staff_id, job_title,
> firstnames, lastname having (count(staff.staff_id) %
> 2 = 1);
>
> This succeeds because for each grouping, which again
> is a person-job
> combination, I can eliminate anybody who has been
> assigned and
> deassigned to the same job the same number of
> times...
>
> But here's a case where I can't figure it out... I'm
> trying to generate
> a list of staff members with the "active" staff
> members first... now, I
> can't use my same of mod 2 here, because a person
> can have more than one
> job... so if i have been added to two jobs but not
> removed from any,
> count(add_or_drop) % 2 = 0, but I am active...
>
> Any suggestions?
>
> -jag
>
>
> --
>
--------------------------------------------------------
> Joshua Ginsberg
> rainman@owlnet.rice.edu
> Director of Technology dirtech@sa.rice.edu
> Student Association AIM: L0stInTheDesert
> Rice University, Houston, TX
>
========================================================
> "Programming today is a race between software
> engineers
> striving to build bigger and better idiot-proof
> programs
> and the Universe trying to produce bigger and better
> idiots. So far, the Universe is winning." -Rich Cook
>
--------------------------------------------------------
>
>
> ---------------------------(end of
> broadcast)---------------------------
> TIP 6: Have you searched our list archives?
>
> http://www.postgresql.org/search.mpl
__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help...
@ 2001-08-11 17:06 Andrew Gould <andrewgould@yahoo.com>
parent: Thomas Lockhart <lockhart@fourpalms.org>
1 sibling, 0 replies; 70+ messages in thread
From: Andrew Gould @ 2001-08-11 17:06 UTC (permalink / raw)
To: lockhart@fourpalms.org; Joshua Adam Ginsberg <rainman@owlnet.rice.edu>; +Cc: pgsql-general
I like Thomas's idea better than the one I just
posted.
If jobs are one-time projects, I would also create a
unique index on staff_history(staff_id, job_id). This
would help keep the data clean. (This would not work
if jobs are employment positions or projects that an
employee can leave and return to.)
Andrew Gould
--- Thomas Lockhart <lockhart@fourpalms.org> wrote:
> > I've got three tables that I'm working with... the
> first is a table of
> > staff members... firstname, lastname, staffid...
> nothing tough... the
> > second is a table of jobs... job title, jobid...
> nothing tough... the
> > third is a history of job assignments... it's got
> a staffid, a jobid, a
> > timestamp, and a field to denote whether the job
> was added or dropped...
> > this third table exists because it is useful in
> this project to be able
> > to look at a staff member's job history...
> ...
> > Any suggestions?
>
> Perhaps not a helpful one... but I would be inclined
> to reorganize that
> third table to have a "start date" *and* a "stop
> date" field, and ditch
> the "dropped" boolean:
>
> o it would keep you from having to figure out how to
> associate two
> entries in the same table with the same job (the
> added and dropped
> rows). How would you currently prevent a job from
> being entered as
> "dropped" without a corresponding "added" row?
>
> o it would make it easier to do the query you are
> asking about; to tell
> whether someone has an active job, just select on a
> date -- like 'today'
> -- between the start and stop dates.
>
> o it may better match reality; jobs have a duration
> so represent that
> explicitly.
>
> hth
>
> - Thomas
>
> ---------------------------(end of
> broadcast)---------------------------
> TIP 1: subscribe and unsubscribe commands go to
majordomo@postgresql.org
__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help...
@ 2001-08-11 21:35 Lee Harr <missive@frontiernet.net>
parent: Thomas Lockhart <lockhart@fourpalms.org>
1 sibling, 0 replies; 70+ messages in thread
From: missive@frontiernet.net @ 2001-08-11 21:35 UTC (permalink / raw)
To: pgsql-general
On Sat, 11 Aug 2001 16:57:10 +0000 (UTC), <lockhart@fourpalms.org>:
> Perhaps not a helpful one... but I would be inclined to reorganize that
> third table to have a "start date" *and* a "stop date" field, and ditch
> the "dropped" boolean:
>
This is how I would do it, then query for employees with
records that have NULL in the "stop date" field.
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2001-08-30 23:45 G.L. Grobe <gary@grobe.net>
0 siblings, 1 reply; 70+ messages in thread
From: G.L. Grobe @ 2001-08-30 23:45 UTC (permalink / raw)
To: pgsql-general
Hi all,
How would I get TableB.label if all I know about is TableA.name?
I was thinking about a query on TableA first, then within the while
(rs.next()), I'd do another query using the result set from A on B, but I
don't like that much, and it seems kind of slow.
Any help much appreciated!
TableA
idA | name | class
-----------------
11 test1 1
12 test2 1
13 test3 2
14 test4 2
TableB
idB | idA | label
----------------
1 11 nameA
2 12 nameB
3 13 nameC
4 14 nameD
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2001-08-31 00:22 Stephan Szabo <sszabo@megazone23.bigpanda.com>
parent: G.L. Grobe <gary@grobe.net>
0 siblings, 0 replies; 70+ messages in thread
From: Stephan Szabo @ 2001-08-31 00:22 UTC (permalink / raw)
To: G.L. Grobe <gary@grobe.net>; +Cc: pgsql-general
Maybe this?
select label from TableB, TableA
where TableB.idA=TableA.idA
and TableA.name=<whatever>
On Thu, 30 Aug 2001, G.L. Grobe wrote:
> Hi all,
>
> How would I get TableB.label if all I know about is TableA.name?
>
> I was thinking about a query on TableA first, then within the while
> (rs.next()), I'd do another query using the result set from A on B, but I
> don't like that much, and it seems kind of slow.
>
> Any help much appreciated!
>
> TableA
> idA | name | class
> -----------------
> 11 test1 1
> 12 test2 1
> 13 test3 2
> 14 test4 2
>
> TableB
> idB | idA | label
> ----------------
> 1 11 nameA
> 2 12 nameB
> 3 13 nameC
> 4 14 nameD
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2001-08-31 12:41 wsheldah@lexmark.com
0 siblings, 0 replies; 70+ messages in thread
From: wsheldah@lexmark.com @ 2001-08-31 12:41 UTC (permalink / raw)
To: G.L. Grobe <gary@grobe.net>; +Cc: pgsql-general
For one specific label:
select TableB.label from TableA, TableB where TableA.idA=TableB.idA and
TableA.name='test2';
To get a list of name-label pairs:
select TableA.name, TableB.label from TableA, TableB where TableA.idA=TableB.idA
order by TableA.name, TableB.label;
"G.L. Grobe" <gary%grobe.net@interlock.lexmark.com> on 08/30/2001 07:45:20 PM
To: pgsql-general%postgresql.org@interlock.lexmark.com
cc: (bcc: Wesley Sheldahl/Lex/Lexmark)
Subject: [GENERAL] query help
Hi all,
How would I get TableB.label if all I know about is TableA.name?
I was thinking about a query on TableA first, then within the while
(rs.next()), I'd do another query using the result set from A on B, but I
don't like that much, and it seems kind of slow.
Any help much appreciated!
TableA
idA | name | class
-----------------
11 test1 1
12 test2 1
13 test3 2
14 test4 2
TableB
idB | idA | label
----------------
1 11 nameA
2 12 nameB
3 13 nameC
4 14 nameD
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddressHere" to majordomo@postgresql.org)
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2001-09-07 15:09 Jeff Patterson <jpat@mpip.org>
0 siblings, 1 reply; 70+ messages in thread
From: Jeff Patterson @ 2001-09-07 15:09 UTC (permalink / raw)
To: pgsql-general
This seems like such a basic function that I'm sure I am missing something
fundamental. I have a table, say xref, whose columns are primary key values for
other tables. Some of theses keys may be NULL for a given row in xref. I want
to create a query that returns the corresponding entries in the other tables.
xref:
drug_id | function_id|syst_id |text_id
--------------------------
d0001 | 2 | 3 | 3423
d0001 | 5 | | 5678
d0056 | 3 | 5 |
system_id:
syst_id | syst_desc
--------------
3 | renal
4 | hepatic
5 | respiratory
clinical_text:
text_id| clinical_text
--------------
3423 | 'some medical mumbo jumbo'
5678 | 'more of the same'
I want the syst_desc and clinical_text (plus other similar data from tables not
shown) given a drug_id and function_id.
Any help?
Thanks a bunch,
Jeff Patterson
The Melanoma Patients' Information Page
http://www.mpip.org
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2001-09-07 15:43 Jeff Patterson <jpat@sonic.net>
0 siblings, 2 replies; 70+ messages in thread
From: Jeff Patterson @ 2001-09-07 15:43 UTC (permalink / raw)
To: pgsql-general
This seems like such a basic function that I'm sure I am missing something
fundamental. I have a table, say xref, whose columns are primary key values for
other tables. Some of theses keys may be NULL for a given row in xref. I want
to create a query that returns the corresponding entries in the other tables.
xref:
drug_id | function_id|syst_id |text_id
--------------------------------------
d0001 | 2 | 3 | 3423
d0001 | 5 | | 5678
d0056 | 3 | 5 |
system_id:
syst_id | syst_desc
-------------------
3 | renal
4 | hepatic
5 | respiratory
clinical_text:
text_id| clinical_text
-----------------------------------
3423 | 'some medical mumbo jumbo'
5678 | 'more of the same'
I want the syst_desc and clinical_text (plus other similar data from tables not
shown) given a drug_id and function_id.
Any help?
Thanks a bunch,
Jeff Patterson
The Melanoma Patients' Information Page
http://www.mpip.org
--
Jeff Patterson
Site Administrator
The Melanoma Patients' Information Page
http://www.mpip.org/
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2001-09-07 16:33 Stephan Szabo <sszabo@megazone23.bigpanda.com>
parent: Jeff Patterson <jpat@sonic.net>
1 sibling, 0 replies; 70+ messages in thread
From: Stephan Szabo @ 2001-09-07 16:33 UTC (permalink / raw)
To: Jeff Patterson <jpat@sonic.net>; +Cc: pgsql-general
On Fri, 7 Sep 2001, Jeff Patterson wrote:
> This seems like such a basic function that I'm sure I am missing something
> fundamental. I have a table, say xref, whose columns are primary key values for
> other tables. Some of theses keys may be NULL for a given row in xref. I want
> to create a query that returns the corresponding entries in the other tables.
>
> xref:
> drug_id | function_id|syst_id |text_id
> --------------------------------------
> d0001 | 2 | 3 | 3423
> d0001 | 5 | | 5678
> d0056 | 3 | 5 |
>
> system_id:
> syst_id | syst_desc
> -------------------
> 3 | renal
> 4 | hepatic
> 5 | respiratory
>
> clinical_text:
> text_id| clinical_text
> -----------------------------------
> 3423 | 'some medical mumbo jumbo'
> 5678 | 'more of the same'
>
> I want the syst_desc and clinical_text (plus other similar data from tables not
> shown) given a drug_id and function_id.
Something like (untested)
select drug_id, function_id, syst_desc, clinical_text from
(xref left outer join system_id using (syst_id))
left outer join clinical_text using (text_id);
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2001-09-09 13:07 Ian Barwick <SUNGLASSESbarwick@gmx.net>
parent: Jeff Patterson <jpat@sonic.net>
1 sibling, 0 replies; 70+ messages in thread
From: Ian Barwick @ 2001-09-09 13:07 UTC (permalink / raw)
To: pgsql-general
Jeff Patterson wrote:
> This seems like such a basic function that I'm sure I am missing something
> fundamental. I have a table, say xref, whose columns are primary key
> values for other tables. Some of theses keys may be NULL for a given row
> in xref. I want to create a query that returns the corresponding entries
> in the other tables.
>
> xref:
> drug_id | function_id|syst_id |text_id
> --------------------------------------
> d0001 | 2 | 3 | 3423
> d0001 | 5 | | 5678
> d0056 | 3 | 5 |
>
> system_id:
> syst_id | syst_desc
> -------------------
> 3 | renal
> 4 | hepatic
> 5 | respiratory
>
> clinical_text:
> text_id| clinical_text
> -----------------------------------
> 3423 | 'some medical mumbo jumbo'
> 5678 | 'more of the same'
>
> I want the syst_desc and clinical_text (plus other similar data from
> tables not shown) given a drug_id and function_id.
>
> Any help?
If I understand you correctly, you want the query to return the syst_desc
and clinical_text fields where either or both are available? (and not just
where both are available)?
If so a LEFT JOIN may be your best friend. The statement could look like
this:
SELECT system_id.syst_desc,
clinical_text.clinical_text
FROM xref
LEFT JOIN system_id
ON xref.syst_id=system_id.syst_id
LEFT JOIN clinical_text
ON xref.text_id=clinical_text.text_id
WHERE xref.drug_id=? <- insert query value here
AND xref.function_id=? <- and here
(disclaimer: statement untested)
The values not available will be returned as NULL.
> Thanks a bunch,
a bunch of what? ;-)
HTH
Ian Barwick
--
Ian Barwick - Developer
http://www.akademie.de
Remove SUNGLASSES to reply ;-)
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2001-09-14 19:49 Oliver Elphick <olly@lfix.co.uk>
parent: Jeff Patterson <jpat@mpip.org>
0 siblings, 0 replies; 70+ messages in thread
From: Oliver Elphick @ 2001-09-14 19:49 UTC (permalink / raw)
To: Jeff Patterson <jpat@mpip.org>; +Cc: pgsql-general
Jeff Patterson wrote:
>This seems like such a basic function that I'm sure I am missing something
>fundamental. I have a table, say xref, whose columns are primary key values
>for
>other tables. Some of theses keys may be NULL for a given row in xref. I wan
>t
>to create a query that returns the corresponding entries in the other tables
>.
>
>xref:
>drug_id | function_id|syst_id |text_id
>--------------------------
>d0001 | 2 | 3 | 3423
>d0001 | 5 | | 5678
>d0056 | 3 | 5 |
>
>system_id:
>syst_id | syst_desc
>--------------
>3 | renal
>4 | hepatic
>5 | respiratory
>
>clinical_text:
>text_id| clinical_text
>--------------
>3423 | 'some medical mumbo jumbo'
>5678 | 'more of the same'
>
>I want the syst_desc and clinical_text (plus other similar data from tables
>not
>shown) given a drug_id and function_id.
>
>Any help?
junk=# select x.drug_id, x.function_id, s.syst_desc, c.clinical_text from xref as x left join system_id as s on x.syst_id = s.syst_id left join clinical_text as c on x.text_id = c.text_id;
drug_id | function_id | syst_desc | clinical_text
---------+-------------+-------------+--------------------------
d0001 | 2 | renal | some medical mumbo jumbo
d0001 | 5 | | more of the same
d0056 | 3 | respiratory |
(3 rows)
--
Oliver Elphick Oliver.Elphick@lfix.co.uk
Isle of Wight http://www.lfix.co.uk/oliver
PGP: 1024R/32B8FAA1: 97 EA 1D 47 72 3F 28 47 6B 7E 39 CC 56 E4 C1 47
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
========================================
"But without faith it is impossible to please him; for
he that cometh to God must believe that he is, and
that he is a rewarder of them that diligently seek
him." Hebrews 11:6
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query Help
@ 2001-12-17 16:21 Joe Koenig <joe@jwebmedia.com>
0 siblings, 2 replies; 70+ messages in thread
From: Joe Koenig @ 2001-12-17 16:21 UTC (permalink / raw)
To: pgsql-general
I have an existing query to pull some product info from my db - there is
a field, item.pack_num, that tells whether the item is new (1) or used
(2). When I display the listing to the web users, I want to be able to
tell them if a used item is available for each item in the list.
However, I want this to all be done with 1 query - so what I'm wondering
is, is there a way to modify my exising query (below) to have it give
the the item with the pack_num of 2, if there are new and used items in
the db. The DISTINCT ON(item.description) is there because if there is a
new and used item, the item is listed in the db twice, once for each
pack_num (I know, bad layout - not my idea...). I don't want the query
to only return used items. The ideal thing would be for it to return all
pack_num's available for that item, but only 1 title (description). I
think that is asking a bit much though. Thanks.
SELECT DISTINCT ON(item.description) item.description AS description,
item.item_num AS item_num, item.comments AS comments, item.pack_num AS
pack_num, dept.description AS category, price.price AS price FROM item,
dept, price WHERE item.dept_num = '91' AND item.sub_dept_num = '200' AND
item.dept_num = dept.dept_num AND item.item_num = price.item_num AND
item.pack_num = price.pack_num;
Also, if something is horribly wrong with my query don't hesitate to
tell me. Thanks Again,
Joe
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2001-12-17 16:29 Chris Albertson <chrisalbertson90278@yahoo.com>
parent: Joe Koenig <joe@jwebmedia.com>
1 sibling, 1 reply; 70+ messages in thread
From: Chris Albertson @ 2001-12-17 16:29 UTC (permalink / raw)
To: joe@jwebmedia.com; pgsql-general
Try this:
1) Remove DISTINCT ON(item.description)
2) Add "GROUP BY item.description"
3) Add (after SELECT) "count(pack_num),"
--- Joe Koenig <joe@jwebmedia.com> wrote:
> I have an existing query to pull some product info from my db - there
> is
> a field, item.pack_num, that tells whether the item is new (1) or
> used
> (2). When I display the listing to the web users, I want to be able
> to
> tell them if a used item is available for each item in the list.
> However, I want this to all be done with 1 query - so what I'm
> wondering
> is, is there a way to modify my exising query (below) to have it give
> the the item with the pack_num of 2, if there are new and used items
> in
> the db. The DISTINCT ON(item.description) is there because if there
> is a
> new and used item, the item is listed in the db twice, once for each
> pack_num (I know, bad layout - not my idea...). I don't want the
> query
<SNIP>
=====
Chris Albertson
Home: 310-376-1029 chrisalbertson90278@yahoo.com
Cell: 310-990-7550
Office: 310-336-5189 Christopher.J.Albertson@aero.org
__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2001-12-17 16:42 Andrew Gould <andrewgould@yahoo.com>
parent: Joe Koenig <joe@jwebmedia.com>
1 sibling, 0 replies; 70+ messages in thread
From: Andrew Gould @ 2001-12-17 16:42 UTC (permalink / raw)
To: joe@jwebmedia.com; pgsql-general
Joe,
Have you considered showing the number of used and new
items in 2 fields (new and used) for item.pack_num:
sum(case when item.pack_num = 1 then 1 else 0 end) as
new,
sum(case when item.pack_num = 2 then 1 else 0 end) as
used
If you try this approach, you'll need aggregate or use
GROUP BY for all other fields.
Best of luck,
Andrew Gould
--- Joe Koenig <joe@jwebmedia.com> wrote:
> I have an existing query to pull some product info
> from my db - there is
> a field, item.pack_num, that tells whether the item
> is new (1) or used
> (2). When I display the listing to the web users, I
> want to be able to
> tell them if a used item is available for each item
> in the list.
> However, I want this to all be done with 1 query -
> so what I'm wondering
> is, is there a way to modify my exising query
> (below) to have it give
> the the item with the pack_num of 2, if there are
> new and used items in
> the db. The DISTINCT ON(item.description) is there
> because if there is a
> new and used item, the item is listed in the db
> twice, once for each
> pack_num (I know, bad layout - not my idea...). I
> don't want the query
> to only return used items. The ideal thing would be
> for it to return all
> pack_num's available for that item, but only 1 title
> (description). I
> think that is asking a bit much though. Thanks.
>
> SELECT DISTINCT ON(item.description)
> item.description AS description,
> item.item_num AS item_num, item.comments AS
> comments, item.pack_num AS
> pack_num, dept.description AS category, price.price
> AS price FROM item,
> dept, price WHERE item.dept_num = '91' AND
> item.sub_dept_num = '200' AND
> item.dept_num = dept.dept_num AND item.item_num =
> price.item_num AND
> item.pack_num = price.pack_num;
>
> Also, if something is horribly wrong with my query
> don't hesitate to
> tell me. Thanks Again,
>
> Joe
>
> ---------------------------(end of
> broadcast)---------------------------
> TIP 1: subscribe and unsubscribe commands go to
majordomo@postgresql.org
__________________________________________________
Do You Yahoo!?
Check out Yahoo! Shopping and Yahoo! Auctions for all of
your unique holiday gifts! Buy at http://shopping.yahoo.com
or bid at http://auctions.yahoo.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2001-12-17 20:33 Joe Koenig <joe@jwebmedia.com>
parent: Chris Albertson <chrisalbertson90278@yahoo.com>
0 siblings, 2 replies; 70+ messages in thread
From: Joe Koenig @ 2001-12-17 20:33 UTC (permalink / raw)
To: pgsql-general
Thanks for the responses - I was able to patch something together from
the responses. On to the next thing - I want to do a search based on a
reg ex. Does PostgreSQL have something like MySQL's "RLIKE"? I want to
pull all records in a category that start with a number 0-9. The best
way I saw was to do a UNION with all the numbers, but I figured there
was a better way. Thanks,
Joe
Chris Albertson wrote:
>
> Try this:
>
> 1) Remove DISTINCT ON(item.description)
> 2) Add "GROUP BY item.description"
> 3) Add (after SELECT) "count(pack_num),"
>
> --- Joe Koenig <joe@jwebmedia.com> wrote:
> > I have an existing query to pull some product info from my db - there
> > is
> > a field, item.pack_num, that tells whether the item is new (1) or
> > used
> > (2). When I display the listing to the web users, I want to be able
> > to
> > tell them if a used item is available for each item in the list.
> > However, I want this to all be done with 1 query - so what I'm
> > wondering
> > is, is there a way to modify my exising query (below) to have it give
> > the the item with the pack_num of 2, if there are new and used items
> > in
> > the db. The DISTINCT ON(item.description) is there because if there
> > is a
> > new and used item, the item is listed in the db twice, once for each
> > pack_num (I know, bad layout - not my idea...). I don't want the
> > query
> <SNIP>
>
> =====
> Chris Albertson
> Home: 310-376-1029 chrisalbertson90278@yahoo.com
> Cell: 310-990-7550
> Office: 310-336-5189 Christopher.J.Albertson@aero.org
>
> __________________________________________________
> Do You Yahoo!?
> Check out Yahoo! Shopping and Yahoo! Auctions for all of
> your unique holiday gifts! Buy at http://shopping.yahoo.com
> or bid at http://auctions.yahoo.com
>
> ---------------------------(end of broadcast)---------------------------
> TIP 5: Have you checked our extensive FAQ?
>
> http://www.postgresql.org/users-lounge/docs/faq.html
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2001-12-17 21:10 Darren Ferguson <darren@crystalballinc.com>
parent: Joe Koenig <joe@jwebmedia.com>
1 sibling, 0 replies; 70+ messages in thread
From: Darren Ferguson @ 2001-12-17 21:10 UTC (permalink / raw)
To: Joe Koenig <joe@jwebmedia.com>; +Cc: pgsql-general
Postgres supports regular expressions
Check out section 4.5.2 POSIX reglar expressions
Darren
Darren Ferguson
Software Engineer
Openband
On Mon, 17 Dec 2001, Joe Koenig wrote:
> Thanks for the responses - I was able to patch something together from
> the responses. On to the next thing - I want to do a search based on a
> reg ex. Does PostgreSQL have something like MySQL's "RLIKE"? I want to
> pull all records in a category that start with a number 0-9. The best
> way I saw was to do a UNION with all the numbers, but I figured there
> was a better way. Thanks,
>
> Joe
>
> Chris Albertson wrote:
> >
> > Try this:
> >
> > 1) Remove DISTINCT ON(item.description)
> > 2) Add "GROUP BY item.description"
> > 3) Add (after SELECT) "count(pack_num),"
> >
> > --- Joe Koenig <joe@jwebmedia.com> wrote:
> > > I have an existing query to pull some product info from my db - there
> > > is
> > > a field, item.pack_num, that tells whether the item is new (1) or
> > > used
> > > (2). When I display the listing to the web users, I want to be able
> > > to
> > > tell them if a used item is available for each item in the list.
> > > However, I want this to all be done with 1 query - so what I'm
> > > wondering
> > > is, is there a way to modify my exising query (below) to have it give
> > > the the item with the pack_num of 2, if there are new and used items
> > > in
> > > the db. The DISTINCT ON(item.description) is there because if there
> > > is a
> > > new and used item, the item is listed in the db twice, once for each
> > > pack_num (I know, bad layout - not my idea...). I don't want the
> > > query
> > <SNIP>
> >
> > =====
> > Chris Albertson
> > Home: 310-376-1029 chrisalbertson90278@yahoo.com
> > Cell: 310-990-7550
> > Office: 310-336-5189 Christopher.J.Albertson@aero.org
> >
> > __________________________________________________
> > Do You Yahoo!?
> > Check out Yahoo! Shopping and Yahoo! Auctions for all of
> > your unique holiday gifts! Buy at http://shopping.yahoo.com
> > or bid at http://auctions.yahoo.com
> >
> > ---------------------------(end of broadcast)---------------------------
> > TIP 5: Have you checked our extensive FAQ?
> >
> > http://www.postgresql.org/users-lounge/docs/faq.html
>
> ---------------------------(end of broadcast)---------------------------
> TIP 6: Have you searched our list archives?
>
> http://archives.postgresql.org
>
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2001-12-18 09:35 Antonio Fiol Bonnín <fiol@w3ping.com>
parent: Joe Koenig <joe@jwebmedia.com>
1 sibling, 0 replies; 70+ messages in thread
From: Antonio Fiol Bonnín @ 2001-12-18 09:35 UTC (permalink / raw)
To: joe@jwebmedia.com; +Cc: pgsql-general
For your very particular purpose, you may try to use
----------------
select * from table where substring(column, 0,1) between '0' and '9';
----------------
For a more general purpose, try the ~ operator.
\do will give you a list of available operators
You should maybe care about ~* operator also (case insensitive).
If you need to match one among many regular expressions, you can try to
store them in a little table, and then try:
----------------
select distinct table.* from table, regex_table where table.column ~
regex_table.regex;
----------------
DISTINCT is there to avoid that entries matching multiple regexps appear
multiple times.
No guarantees on performance.
HTH,
Antonio
Joe Koenig wrote:
>Thanks for the responses - I was able to patch something together from
>the responses. On to the next thing - I want to do a search based on a
>reg ex. Does PostgreSQL have something like MySQL's "RLIKE"? I want to
>pull all records in a category that start with a number 0-9. The best
>way I saw was to do a UNION with all the numbers, but I figured there
>was a better way. Thanks,
>
>Joe
>
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query Help
@ 2002-07-23 23:39 Hunter Hillegas <lists@lastonepicked.com>
0 siblings, 1 reply; 70+ messages in thread
From: Hunter Hillegas @ 2002-07-23 23:39 UTC (permalink / raw)
To: pgsql-general
I'm looking for a little query help, if anyone has a free moment...
I have two tables:
CREATE TABLE message_board_topics (
rec_num integer NOT NULL PRIMARY KEY,
topic_name varchar(255),
topic_body text,
topic_author varchar(20),
topic_author_email varchar(50),
topic_date date,
topic_updated datetime,
number_of_comments integer
);
CREATE TABLE message_board_comments (
rec_num integer NOT NULL PRIMARY KEY,
topic_id integer REFERENCES message_board_topics,
comment_parent integer,
comment_name varchar(255),
comment_body text,
comment_author varchar(20),
comment_author_email varchar(50),
comment_date date
);
Anyway, I want to do a quick and dirty search against them... Basically I
want to find any message_board_topic where the submitted text matches either
the topic_name, topic_body, topic_author, or the comment_author of any
related comment...
I tried this:
SELECT * FROM message_board_topics, message_board_comments WHERE
upper(topic_name) LIKE upper('%test%') OR upper(topic_body) LIKE
upper('%test%') OR upper(topic_author) LIKE upper('%test%') OR
(upper(message_board_comments.comment_author) LIKE upper('%test%') AND
message_board_comments.topic_id = message_board_topics.rec_num) ORDER BY
message_board_topics.rec_num DESC;
Now, this returns no rows but this query that doesn't search the comments
table returns a row:
SELECT * FROM message_board_topics WHERE upper(topic_name) LIKE
upper('%test%') OR upper(topic_body) LIKE upper('%test%') OR
upper(topic_author) LIKE upper('%test%') ORDER BY
message_board_topics.rec_num DESC;
Any ideas what I am doing wrong? It would be a big help.
Thanks,
Hunter
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2002-07-24 00:28 Stephan Szabo <sszabo@megazone23.bigpanda.com>
parent: Hunter Hillegas <lists@lastonepicked.com>
0 siblings, 0 replies; 70+ messages in thread
From: Stephan Szabo @ 2002-07-24 00:28 UTC (permalink / raw)
To: Hunter Hillegas <lists@lastonepicked.com>; +Cc: pgsql-general
On Tue, 23 Jul 2002, Hunter Hillegas wrote:
> I'm looking for a little query help, if anyone has a free moment...
>
> I have two tables:
>
> CREATE TABLE message_board_topics (
> rec_num integer NOT NULL PRIMARY KEY,
> topic_name varchar(255),
> topic_body text,
> topic_author varchar(20),
> topic_author_email varchar(50),
> topic_date date,
> topic_updated datetime,
> number_of_comments integer
> );
>
> CREATE TABLE message_board_comments (
> rec_num integer NOT NULL PRIMARY KEY,
> topic_id integer REFERENCES message_board_topics,
> comment_parent integer,
> comment_name varchar(255),
> comment_body text,
> comment_author varchar(20),
> comment_author_email varchar(50),
> comment_date date
> );
>
> Anyway, I want to do a quick and dirty search against them... Basically I
> want to find any message_board_topic where the submitted text matches either
> the topic_name, topic_body, topic_author, or the comment_author of any
> related comment...
>
> I tried this:
>
> SELECT * FROM message_board_topics, message_board_comments WHERE
> upper(topic_name) LIKE upper('%test%') OR upper(topic_body) LIKE
> upper('%test%') OR upper(topic_author) LIKE upper('%test%') OR
> (upper(message_board_comments.comment_author) LIKE upper('%test%') AND
> message_board_comments.topic_id = message_board_topics.rec_num) ORDER BY
> message_board_topics.rec_num DESC;
>
> Now, this returns no rows but this query that doesn't search the comments
> table returns a row:
>
> SELECT * FROM message_board_topics WHERE upper(topic_name) LIKE
> upper('%test%') OR upper(topic_body) LIKE upper('%test%') OR
> upper(topic_author) LIKE upper('%test%') ORDER BY
> message_board_topics.rec_num DESC;
>
> Any ideas what I am doing wrong? It would be a big help.
Presumably there's no comment for the matching row. You're doing
an inner join in the first query so it's only going to give you
a row out if there exists a comment whose topic_id is equal to
the other table's rec_num.
You might want to do an outer join instead (something like:
select * from message_board_topics left join message_board_comments
on (message_board_comments.topic_id=message_board_topics.rec_num)
where
upper(topic_name) LIKE upper('%test%') OR upper(topic_body) LIKE
upper('%test%') OR upper(topic_author) LIKE upper('%test%') OR
(upper(message_board_comments.comment_author) LIKE upper('%test%')
order by message_board_topics.rec_num desc;
^ permalink raw reply [nested|flat] 70+ messages in thread
* [OFFTOPIC] Query Help
@ 2002-12-03 23:16 Hunter Hillegas <lists@lastonepicked.com>
0 siblings, 1 reply; 70+ messages in thread
From: Hunter Hillegas @ 2002-12-03 23:16 UTC (permalink / raw)
To: pgsql-general
Someone asked me to create a query for them that would compute some averages
for them over time.
Basically I have a view that looks like this:
sample_request_line_item_number | integer |
sample_origin | character varying |
date_of_request | timestamp with time zone |
username | character varying |
date_shipped | date |
date_difference | double precision |
I have a query that does what I need:
select username, avg(date_difference) from sample_request_average_days where
date_shipped between '2002-11-01' and '2002-11-30' group by username;
Basically it is getting the average number of days it took to ship something
by salesperson, by month.
The problem is that I want it to print the results for each month for which
there are entries (without hard-coding dates).
Is there any easy way to do this that I'm missing?
Any help appreciated. Please reply off-list to minimize noise.
Thanks,
Hunter
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: [OFFTOPIC] Query Help
@ 2002-12-03 23:29 Jean-Luc Lachance <jllachan@nsd.ca>
parent: Hunter Hillegas <lists@lastonepicked.com>
0 siblings, 0 replies; 70+ messages in thread
From: Jean-Luc Lachance @ 2002-12-03 23:29 UTC (permalink / raw)
To: Hunter Hillegas <lists@lastonepicked.com>; +Cc: pgsql-general
Try:
select username, avg(date_difference) from sample_request_average_days
group by salesperson, to_char( date_shipped, 'YYYYMM');
Hunter Hillegas wrote:
>
> Someone asked me to create a query for them that would compute some averages
> for them over time.
>
> Basically I have a view that looks like this:
>
> sample_request_line_item_number | integer |
> sample_origin | character varying |
> date_of_request | timestamp with time zone |
> username | character varying |
> date_shipped | date |
> date_difference | double precision |
>
> I have a query that does what I need:
>
>
> date_shipped between '2002-11-01' and '2002-11-30' group by username;
>
> Basically it is getting the average number of days it took to ship something
> by salesperson, by month.
>
> The problem is that I want it to print the results for each month for which
> there are entries (without hard-coding dates).
>
> Is there any easy way to do this that I'm missing?
>
> Any help appreciated. Please reply off-list to minimize noise.
>
> Thanks,
> Hunter
>
> ---------------------------(end of broadcast)---------------------------
> TIP 1: subscribe and unsubscribe commands go to majordomo@postgresql.org
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query Help
@ 2003-03-29 07:42 shreedhar <shreedhar@lucidindia.net>
0 siblings, 1 reply; 70+ messages in thread
From: shreedhar @ 2003-03-29 07:42 UTC (permalink / raw)
To: pgsql-general
Hi All
SELECT TotalErrors.Year, TotalErrors.month, TotalReported, ClosedErrors, OpenErrors, FixedErrors FROM
( SELECT DISTINCT EXTRACT( MON FROM logdate ) AS month, EXTRACT ( YEAR FROM logdate) AS year, COUNT(tblInformation.Inforid ) AS TotalReported
FROM tblInformation
INNER JOIN tblError ON tblInformation.inforid = tblError.inforid
INNER JOIN tblErrorStatus ON tblErrorStatus.statusid = tblError.statusid
INNER JOIN tblJobInformation ON tblJobInformation.inforid = tblInformation.inforid
WHERE logdate >= '2002-01-01' AND logdate < now() AND tblJobInformation.projectid = 33
GROUP BY year, month ) AS TotalErrors
LEFT JOIN
( SELECT DISTINCT EXTRACT( MON FROM logdate ) AS month , EXTRACT ( YEAR FROM logdate) AS year, COUNT(tblInformation.Inforid ) AS ClosedErrors
FROM tblInformation
INNER JOIN tblError ON tblInformation.inforid = tblError.inforid
INNER JOIN tblErrorStatus ON tblErrorStatus.statusid = tblError.statusid
INNER JOIN tblJobInformation ON tblJobInformation.inforid = tblInformation.inforid
WHERE logdate >= '2002-01-01' AND logdate < now() AND tblError.statusid = 2 AND tblJobInformation.projectid = 33
GROUP BY year, month ) As ClosedErrors
ON TotalErrors.month = ClosedErrors.month
LEFT JOIN
( SELECT DISTINCT EXTRACT( MON FROM logdate ) AS month, EXTRACT ( YEAR FROM logdate) AS year, COUNT(tblInformation.Inforid ) AS OpenErrors
FROM tblInformation
INNER JOIN tblError ON tblInformation.inforid = tblError.inforid
INNER JOIN tblErrorStatus ON tblErrorStatus.statusid = tblError.statusid
INNER JOIN tblJobInformation ON tblJobInformation.inforid = tblInformation.inforid
WHERE logdate >= '2002-01-01' AND logdate < now() AND tblError.statusid = 6 AND tblJobInformation.projectid = 33
GROUP BY year, month ) AS OpenErrors
ON TotalErrors.month = OpenErrors.month
LEFT JOIN
( SELECT DISTINCT EXTRACT( MON FROM logdate ) AS month, EXTRACT ( YEAR FROM logdate) AS year, COUNT(tblInformation.Inforid ) AS FixedErrors
FROM tblInformation
INNER JOIN tblError ON tblInformation.inforid = tblError.inforid
INNER JOIN tblErrorStatus ON tblErrorStatus.statusid = tblError.statusid
INNER JOIN tblJobInformation ON tblJobInformation.inforid = tblInformation.inforid
WHERE logdate >= '2002-01-01' AND logdate < now() AND tblError.statusid = 5 AND tblJobInformation.projectid = 33
GROUP BY year, month ) AS FixedErrors
ON TotalErrors.month = FixedErrors.month
ORDER BY TotalErrors.Year, TotalErrors.month
Using this query I am expecting result as
year month totalreported closederrors openerrors fixederrors
2002 1 31 29 2
2002 2 85 60 25
2002 3 16 12 4
2002 5 41 29 12
2002 7 48 48
2002 8 1 1
2002 10 51 51
2002 11 69 15 54
2002 12 8 8
2003 1 9 9
2003 2 38 38
But Retreiving result as
year month totalreported closederrors openerrors fixederrors
2002 1 31 29 2
2002 1 31 29 9
2002 2 85 60 25
2002 2 85 60 38
2002 3 16 12 4
2002 5 41 29 12
2002 7 48 48
2002 8 1 1
2002 10 51 51
2002 11 69 15 54
2002 12 8 8
2003 1 9 29 2
2003 1 9 29 9
2003 2 38 60 25
2003 2 38 60 38
I mean I values retreives across years data is repeating.
May I know how can I get expected results by above query.
Regards,
Sreedhar
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2003-03-29 15:53 Stephan Szabo <sszabo@megazone23.bigpanda.com>
parent: shreedhar <shreedhar@lucidindia.net>
0 siblings, 0 replies; 70+ messages in thread
From: Stephan Szabo @ 2003-03-29 15:53 UTC (permalink / raw)
To: shreedhar <shreedhar@lucidindia.net>; +Cc: pgsql-general
On Sat, 29 Mar 2003, shreedhar wrote:
> Using this query I am expecting result as
>
> year month totalreported closederrors openerrors fixederrors
> 2002 1 31 29 2
>
> 2002 2 85 60 25
>
> 2002 3 16 12 4
> 2002 5 41 29 12
> 2002 7 48 48
> 2002 8 1 1
> 2002 10 51 51
> 2002 11 69 15 54
> 2002 12 8 8
>
> 2003 1 9 9
>
> 2003 2 38 38
>
>
>
> But Retreiving result as
>
> year month totalreported closederrors openerrors fixederrors
> 2002 1 31 29 2
> 2002 1 31 29 9
> 2002 2 85 60 25
> 2002 2 85 60 38
> 2002 3 16 12 4
> 2002 5 41 29 12
> 2002 7 48 48
> 2002 8 1 1
> 2002 10 51 51
> 2002 11 69 15 54
> 2002 12 8 8
> 2003 1 9 29 2
> 2003 1 9 29 9
> 2003 2 38 60 25
> 2003 2 38 60 38
>
>
>
> I mean I values retreives across years data is repeating.
>
> May I know how can I get expected results by above query.
Hmm, what version are you using and what are the definitions of the tables
and what do the component subselects generate? I don't see anything
obviously wrong (although I'd think that the distinct clauses are
unnecessary with the group by), so I could have missed something or you
could be hitting a bug, but without something to plug in to try with it's
hard to tell.
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2003-05-14 10:55 Rob Larter <rob@cdli.co.uk>
0 siblings, 1 reply; 70+ messages in thread
From: Rob Larter @ 2003-05-14 10:55 UTC (permalink / raw)
To: pgsql-general
hi i am trying to execute the following query:
select source,(b.source/c.total),(select count(*) from entries b where
source = a.source) as source,(select count(*) from entries c) as total from
entries a group by source;
it says
ERROR: Relation "b" does not exist
the query:
select source,(select count(*) from entries where source = a.source) as
source,(select count(*) from entries) as total from entries a group by
source;
works fine but i want to use the result from source and entries to work out
a percentage in the sql query
could someone point me in the right direction?
Thanks!
Rob
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2003-05-14 15:41 Stephan Szabo <sszabo@megazone23.bigpanda.com>
parent: Rob Larter <rob@cdli.co.uk>
0 siblings, 0 replies; 70+ messages in thread
From: Stephan Szabo @ 2003-05-14 15:41 UTC (permalink / raw)
To: Rob Larter <rob@cdli.co.uk>; +Cc: pgsql-general
On Wed, 14 May 2003, Rob Larter wrote:
> hi i am trying to execute the following query:
>
> select source,(b.source/c.total),(select count(*) from entries b where
> source = a.source) as source,(select count(*) from entries c) as total from
> entries a group by source;
>
> it says
> ERROR: Relation "b" does not exist
Right, because it doesn't escape the subselect.
Maybe something like:
select source, ecount/etotalcount, ecount as source, etotalcount as total
from
(select source, count(*) as ecount from entries group by source) as t,
(select count(*) as etotalcount from entries) as t1;
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query Help
@ 2007-01-19 17:05 Howard Cole <howardnews@selestial.com>
0 siblings, 1 reply; 70+ messages in thread
From: Howard Cole @ 2007-01-19 17:05 UTC (permalink / raw)
To: pgsql-general
Hi All,
I am getting an error I do not understand from the following setup
CREATE TABLE timesheet_booking
(
timesheet_booking_id bigserial NOT NULL,
operator_id integer,
booking_item_id integer,
"day" date NOT NULL,
minutes integer NOT NULL,
CONSTRAINT timesheet_booking_pkey PRIMARY KEY (timesheet_booking_id),
CONSTRAINT timesheet_booking_booking_item_id_fkey FOREIGN KEY
(booking_item_id)
REFERENCES booking_item (booking_item_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT timesheet_booking_operator_id_fkey FOREIGN KEY (operator_id)
REFERENCES "operator" (operator_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE SET NULL
)
WITHOUT OIDS;
CREATE UNIQUE INDEX timesheet_booking_unique_idx
ON timesheet_booking
USING btree
(operator_id, booking_item_id, "day");
Now the timesheet booking contains the following data:
timesheet_booking_id, operator_id,booking_item_id,day,minutes
2;284;1;"2007-01-18";10
4;284;2;"2007-01-18";10
If I try the following query:
delete from operator where operator_id=283;
I get the following error message:
ERROR: could not open relation with OID 438427
SQL state: XX000
Context: SQL statement "UPDATE ONLY "public"."timesheet_booking" SET
"operator_id" = NULL WHERE "operator_id" = $1"
If I try this sql statement directly it works OK. What does this error
mean and how can I get rid of it?
Thanks
Howard.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2007-01-19 18:52 Tom Lane <tgl@sss.pgh.pa.us>
parent: Howard Cole <howardnews@selestial.com>
0 siblings, 1 reply; 70+ messages in thread
From: Tom Lane @ 2007-01-19 18:52 UTC (permalink / raw)
To: Howard Cole <howardnews@selestial.com>; +Cc: pgsql-general
Howard Cole <howardnews@selestial.com> writes:
> If I try the following query:
> delete from operator where operator_id=283;
> I get the following error message:
> ERROR: could not open relation with OID 438427
> SQL state: XX000
> Context: SQL statement "UPDATE ONLY "public"."timesheet_booking" SET
> "operator_id" = NULL WHERE "operator_id" = $1"
It looks like you have a stale plan for that ON DELETE SET NULL
constraint. Was there perhaps an index on operator_id that you removed?
Postgres is not very good about flushing cached plans when you change
table schemas (something I hope will be fixed in 8.3).
If that is the problem, starting a fresh session would be enough to take
care of it.
regards, tom lane
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query Help
@ 2007-01-21 20:08 Howard Cole <howardnews@selestial.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 0 replies; 70+ messages in thread
From: Howard Cole @ 2007-01-21 20:08 UTC (permalink / raw)
To: pgsql-general
Tom Lane wrote:
> It looks like you have a stale plan for that ON DELETE SET NULL
> constraint. Was there perhaps an index on operator_id that you removed?
> Postgres is not very good about flushing cached plans when you change
> table schemas (something I hope will be fixed in 8.3).
>
> If that is the problem, starting a fresh session would be enough to take
> care of it.
>
> regards, tom lane
>
>
Thanks Tom. You were, as usual, correct!
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2007-03-08 06:20 Madison Kelly <linux@alteeve.com>
0 siblings, 2 replies; 70+ messages in thread
From: Madison Kelly @ 2007-03-08 06:20 UTC (permalink / raw)
To: pgsql-general
Hi all,
I've got a query that looks through a table I use for my little
search engine. It's something of a reverse-index but not quite, where a
proper reverse index would have 'word | doc1, doc3, doc4, doc7' showing
all the docs the keyword is in, mine has an entry for eac
I've got a query like:
SELECT
sch_id, sch_for_table, sch_ref_id, sch_instances
FROM
search_index
WHERE
(sch_keyword LIKE '%digi%' OR sch_keyword LIKE '%madi%')
AND
sch_for_table!='client'
AND
... (more restrictions)
ORDER BY
sch_instances DESC;
This returns references to a data column (sch_ref_id) in a given
table (sch_for_table) for each matched keyword.
The problem I am having is that two keywords might reference the same
table/column which would, in turn, give me two+ search results pointing
to the same entry.
What I would like to do is, when two or more results match the same
'sch_ref_id' and 'sch_for_table' to merge the results. Specifically, the
'sch_instances' column is the number of times the given keyword is found
in the table/column. I'd like to add up the number in the duplicate
results (to give it a higher accuracy and move it up the search results).
Is this possible or would I need to add this logic in my program? I'd
rather do it in PostgreSQL though, if I could.
Here is the 'search_index' table I am using:
db=> \d search_index
Table "public.search_index"
Column | Type | Modifiers
---------------+---------+-----------------------------------------------
sch_id | integer | not null default nextval('sch_seq'::regclass)
sch_keyword | text | not null
sch_instances | integer | not null default 1
sch_for_table | text | not null
sch_ref_id | integer | not null
Indexes:
"search_index_pkey" PRIMARY KEY, btree (sch_id)
Thanks in advance to any help you might be able to give me!
Madison
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2007-03-08 06:46 Shaun Johnston <shaunj@benon.com>
parent: Madison Kelly <linux@alteeve.com>
1 sibling, 0 replies; 70+ messages in thread
From: Shaun Johnston @ 2007-03-08 06:46 UTC (permalink / raw)
To: Madison Kelly <linux@alteeve.com>; +Cc: pgsql-general
Try
SELECT DISTINCT
rather than SELECT
That should return a result with unique records.
Madison Kelly wrote:
> Hi all,
>
> I've got a query that looks through a table I use for my little
> search engine. It's something of a reverse-index but not quite, where
> a proper reverse index would have 'word | doc1, doc3, doc4, doc7'
> showing all the docs the keyword is in, mine has an entry for eac
>
> I've got a query like:
>
> SELECT
> sch_id, sch_for_table, sch_ref_id, sch_instances
> FROM
> search_index
> WHERE
> (sch_keyword LIKE '%digi%' OR sch_keyword LIKE '%madi%')
> AND
> sch_for_table!='client'
> AND
> ... (more restrictions)
> ORDER BY
> sch_instances DESC;
>
> This returns references to a data column (sch_ref_id) in a given
> table (sch_for_table) for each matched keyword.
>
> The problem I am having is that two keywords might reference the
> same table/column which would, in turn, give me two+ search results
> pointing to the same entry.
>
> What I would like to do is, when two or more results match the same
> 'sch_ref_id' and 'sch_for_table' to merge the results. Specifically,
> the 'sch_instances' column is the number of times the given keyword is
> found in the table/column. I'd like to add up the number in the
> duplicate results (to give it a higher accuracy and move it up the
> search results).
>
> Is this possible or would I need to add this logic in my program?
> I'd rather do it in PostgreSQL though, if I could.
>
> Here is the 'search_index' table I am using:
>
> db=> \d search_index
> Table "public.search_index"
> Column | Type | Modifiers
> ---------------+---------+-----------------------------------------------
> sch_id | integer | not null default nextval('sch_seq'::regclass)
> sch_keyword | text | not null
> sch_instances | integer | not null default 1
> sch_for_table | text | not null
> sch_ref_id | integer | not null
> Indexes:
> "search_index_pkey" PRIMARY KEY, btree (sch_id)
>
> Thanks in advance to any help you might be able to give me!
>
> Madison
>
> ---------------------------(end of broadcast)---------------------------
> TIP 5: don't forget to increase your free space map settings
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2007-03-08 09:51 Richard Huxton <dev@archonet.com>
parent: Madison Kelly <linux@alteeve.com>
1 sibling, 1 reply; 70+ messages in thread
From: Richard Huxton @ 2007-03-08 09:51 UTC (permalink / raw)
To: Madison Kelly <linux@alteeve.com>; +Cc: pgsql-general
Madison Kelly wrote:
> Hi all,
>
> I've got a query that looks through a table I use for my little search
> engine. It's something of a reverse-index but not quite, where a proper
> reverse index would have 'word | doc1, doc3, doc4, doc7' showing all the
> docs the keyword is in, mine has an entry for eac
>
> I've got a query like:
>
> SELECT
> sch_id, sch_for_table, sch_ref_id, sch_instances
> FROM
> search_index
> WHERE
> (sch_keyword LIKE '%digi%' OR sch_keyword LIKE '%madi%')
> AND
> sch_for_table!='client'
> AND
> ... (more restrictions)
> ORDER BY
> sch_instances DESC;
>
> This returns references to a data column (sch_ref_id) in a given table
> (sch_for_table) for each matched keyword.
>
> The problem I am having is that two keywords might reference the same
> table/column which would, in turn, give me two+ search results pointing
> to the same entry.
>
> What I would like to do is, when two or more results match the same
> 'sch_ref_id' and 'sch_for_table' to merge the results. Specifically, the
> 'sch_instances' column is the number of times the given keyword is found
> in the table/column. I'd like to add up the number in the duplicate
> results (to give it a higher accuracy and move it up the search results).
You'll want something like:
SELECT
sch_id, sch_for_table, sch_ref_id,
SUM(sch_instances) AS tot_instances
...
GROUP BY
sch_id, sch_for_table, sch_ref_id
ORDER BY
tot_instances DESC;
The key word to search the manuals on is "aggregates" (sum(), count() etc).
--
Richard Huxton
Archonet Ltd
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2007-03-09 02:46 Madison Kelly <linux@alteeve.com>
parent: Richard Huxton <dev@archonet.com>
0 siblings, 0 replies; 70+ messages in thread
From: Madison Kelly @ 2007-03-09 02:46 UTC (permalink / raw)
To: Richard Huxton <dev@archonet.com>; +Cc: pgsql-general
Richard Huxton wrote:
> Madison Kelly wrote:
>> Hi all,
>>
>> I've got a query that looks through a table I use for my little
>> search engine. It's something of a reverse-index but not quite, where
>> a proper reverse index would have 'word | doc1, doc3, doc4, doc7'
>> showing all the docs the keyword is in, mine has an entry for eac
>>
>> I've got a query like:
>>
>> SELECT
>> sch_id, sch_for_table, sch_ref_id, sch_instances
>> FROM
>> search_index
>> WHERE
>> (sch_keyword LIKE '%digi%' OR sch_keyword LIKE '%madi%')
>> AND
>> sch_for_table!='client'
>> AND
>> ... (more restrictions)
>> ORDER BY
>> sch_instances DESC;
>>
>> This returns references to a data column (sch_ref_id) in a given
>> table (sch_for_table) for each matched keyword.
>>
>> The problem I am having is that two keywords might reference the
>> same table/column which would, in turn, give me two+ search results
>> pointing to the same entry.
>>
>> What I would like to do is, when two or more results match the same
>> 'sch_ref_id' and 'sch_for_table' to merge the results. Specifically,
>> the 'sch_instances' column is the number of times the given keyword is
>> found in the table/column. I'd like to add up the number in the
>> duplicate results (to give it a higher accuracy and move it up the
>> search results).
>
> You'll want something like:
>
> SELECT
> sch_id, sch_for_table, sch_ref_id,
> SUM(sch_instances) AS tot_instances
> ...
> GROUP BY
> sch_id, sch_for_table, sch_ref_id
> ORDER BY
> tot_instances DESC;
>
> The key word to search the manuals on is "aggregates" (sum(), count() etc).
>
This is *exactly* the pointer I needed, thank you!
Sad thing is that I even used "GROUP BY" before... had just forgotten
about it. ^_^;
Madison
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2007-08-14 20:10 Kirk Wythers <kwythers@umn.edu>
0 siblings, 1 reply; 70+ messages in thread
From: Kirk Wythers @ 2007-08-14 20:10 UTC (permalink / raw)
To: pgsql-general
I need some help with rewriting a query. I have a fairly complicated
query (for me anyway) that dumps daily climate data, filling in
missing data with monthly averages (one line per day).
I want to output monthly averages (one line per month). I am having a
hard time wrapping my head around this. Particularly how to deal with
the doy column (day of year). I have tried several approaches and my
forehead is starting to get my keyboard bloody.
Thanks in advance for any suggestions.
Here is the daily query:
SELECT CASE
WHEN w.station_id = site_near.station_id THEN w.obs_id
ELSE s.obs_id
END AS obs_id,
site_near.station_id,
site_near.longname,
w.year,
w.doy,
--replace missing values (-999) with the monthly average
CASE w.tmax
WHEN -999 THEN avgtmax.avg
ELSE w.tmax
END,
CASE w.tmin
WHEN -999 THEN avgtmin.avg
ELSE w.tmin
END,
CASE s.par
WHEN -999 THEN avgpar.avg
ELSE s.par
END,
CASE w.precip
WHEN -999 THEN avgprecip.avg
ELSE w.precip
END
FROM site_near
INNER JOIN solar s
ON (site_near.ref_solar_station_id = s.station_id
AND site_near.obs_year = s.year)
INNER JOIN weather w
ON (site_near.ref_weather_station_id = w.station_id
AND site_near.obs_year = w.year
AND s.date = w.date)
INNER JOIN (SELECT MONTH,
round(avg(tmax)::numeric, 2) AS avg
FROM weather
WHERE tmax != -999
GROUP BY MONTH) AS avgtmax
ON (w.month = avgtmax.month)
INNER JOIN (SELECT MONTH,
round(avg(tmin)::numeric, 2) AS avg
FROM weather
WHERE tmin != -999
GROUP BY MONTH) AS avgtmin
ON (w.month = avgtmin.month)
INNER JOIN (SELECT MONTH,
round(avg(par)::numeric, 2) AS avg
FROM solar
WHERE par != -999
GROUP BY MONTH) AS avgpar
ON (s.month = avgpar.month)
INNER JOIN (SELECT MONTH,
round(avg(precip)::numeric, 2) AS avg
FROM weather
WHERE precip != -999
GROUP BY MONTH) AS avgprecip
ON (w.month = avgprecip.month)
--select station to output climate data by id number
WHERE w.station_id = 219101
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-08-15 03:20 Josh Tolley <eggyknap@gmail.com>
parent: Kirk Wythers <kwythers@umn.edu>
0 siblings, 0 replies; 70+ messages in thread
From: Josh Tolley @ 2007-08-15 03:20 UTC (permalink / raw)
To: Kirk Wythers <kwythers@umn.edu>; +Cc: pgsql-general
On 8/14/07, Kirk Wythers <kwythers@umn.edu> wrote:
>
> I need some help with rewriting a query. I have a fairly complicated query
> (for me anyway) that dumps daily climate data, filling in missing data with
> monthly averages (one line per day).
>
> I want to output monthly averages (one line per month). I am having a hard
> time wrapping my head around this. Particularly how to deal with the doy
> column (day of year). I have tried several approaches and my forehead is
> starting to get my keyboard bloody.
I think this came up on IRC today, so perhaps this is only for the
archives' sake, but you want to do something like this:
Assuming you have a table as follows:
CREATE TABLE climate_data (
measurement_time timestamp,
measurement_value integer);
...and you insert data into it regularly, you can get the average
measurement over a period of time with date_trunc(), which will
truncate a date or timestamp value to match whatever precision you
specify. For example, see the following:
eggyknap=# select date_trunc('month', now());
date_trunc
------------------------
2007-08-01 00:00:00-06
(1 row)
Note: the -06 at the end means I'm in mountain time.
So if you want to get the average measurement over a month's time, you
need to do something like this:
SELECT DATE_TRUNC('MONTH', measurement_time), AVG(measurement_value)
FROM climate_data GROUP BY DATE_TRUNC('MONTH', measurement_time);
This will chop all the measurement_time values down to the month the
measurement was taken in, put all measurements in groups based on the
resulting value, and take the average measurement_value from each
group.
- Josh
^ permalink raw reply [nested|flat] 70+ messages in thread
* query help
@ 2007-09-13 15:06 volunteer@spatiallink.org
0 siblings, 2 replies; 70+ messages in thread
From: volunteer@spatiallink.org @ 2007-09-13 15:06 UTC (permalink / raw)
To: pgsql-general
hello
table is
+-------+-------+------+-------+
| id | one | two | three |
+-------+-------+------+-------+
| first | Jack | Jill | Mary |
| last | Ja | Ji | Ma |
+-------+-------+------+-------+
result is
+----+-------+-------+
| id | one | two |
+----+-------+-------+
| first | Jack | Jill |
| last | Ja | Ji |
+----+-------+-------+
query is??
sincerely
siva
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:17 Alexander Staubo <alex@purefiction.net>
parent: volunteer@spatiallink.org
1 sibling, 0 replies; 70+ messages in thread
From: Alexander Staubo @ 2007-09-13 15:17 UTC (permalink / raw)
To: volunteer@spatiallink.org <volunteer@spatiallink.org>; +Cc: pgsql-general
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> hello
>
> table is
> +-------+-------+------+-------+
> | id | one | two | three |
> +-------+-------+------+-------+
> | first | Jack | Jill | Mary |
> | last | Ja | Ji | Ma |
> +-------+-------+------+-------+
>
> result is
> +----+-------+-------+
> | id | one | two |
> +----+-------+-------+
> | first | Jack | Jill |
> | last | Ja | Ji |
> +----+-------+-------+
>
> query is??
Unless I am missing something crucial, this is SQL 101:
select id, one, two from foo;
Alexander.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:18 Rodrigo De León <rdeleonp@gmail.com>
parent: volunteer@spatiallink.org
1 sibling, 0 replies; 70+ messages in thread
From: Rodrigo De León @ 2007-09-13 15:18 UTC (permalink / raw)
To: volunteer@spatiallink.org <volunteer@spatiallink.org>; +Cc: pgsql-general
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> query is??
http://www.w3schools.com/sql/default.asp
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:32 volunteer@spatiallink.org
0 siblings, 3 replies; 70+ messages in thread
From: volunteer@spatiallink.org @ 2007-09-13 15:32 UTC (permalink / raw)
To: pgsql-general; +Cc: alex@purefiction.net; rdeleonp@gmail.com
hello
i add more column not row for new user. i want all "last like 'J%'".
http://www.nabble.com/an-other-provokative-question---tf4394285.html
sincerely
siva
-------- Original Message --------
Subject: Re: [GENERAL] query help
From: "Alexander Staubo" <alex@purefiction.net>
Date: Thu, September 13, 2007 11:17 am
To: "volunteer@spatiallink.org" <volunteer@spatiallink.org>
Cc: pgsql-general@postgresql.org
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> hello
>
> table is
> +-------+-------+------+-------+
> | id | one | two | three |
> +-------+-------+------+-------+
> | first | Jack | Jill | Mary |
> | last | Ja | Ji | Ma |
> +-------+-------+------+-------+
>
> result is
> +----+-------+-------+
> | id | one | two |
> +----+-------+-------+
> | first | Jack | Jill |
> | last | Ja | Ji |
> +----+-------+-------+
>
> query is??
Unless I am missing something crucial, this is SQL 101:
select id, one, two from foo;
Alexander.
---------------------------(end of broadcast)---------------------------
TIP 4: Have you searched our list archives?
http://archives.postgresql.org/
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:38 Alexander Staubo <alex@purefiction.net>
parent: volunteer@spatiallink.org
2 siblings, 0 replies; 70+ messages in thread
From: Alexander Staubo @ 2007-09-13 15:38 UTC (permalink / raw)
To: volunteer@spatiallink.org <volunteer@spatiallink.org>; +Cc: pgsql-general
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> i add more column not row for new user. i want all "last like 'J%'".
> http://www.nabble.com/an-other-provokative-question---tf4394285.html
Sorry, but the only difference between your table example and your
result example was the absence, in the results, of one of the columns.
If you want to constrain by some attribute, then you have to tell us
that. I recommend that you buy a book on SQL. Lastly, I don't see what
this has to do with the "provokative question" thread.
Alexander.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:44 Steve Crawford <scrawford@pinpointresearch.com>
parent: volunteer@spatiallink.org
2 siblings, 0 replies; 70+ messages in thread
From: Steve Crawford @ 2007-09-13 15:44 UTC (permalink / raw)
To: volunteer@spatiallink.org; +Cc: pgsql-general; alex@purefiction.net; rdeleonp@gmail.com
volunteer@spatiallink.org wrote:
> hello
> i add more column not row for new user. i want all "last like 'J%'".
> http://www.nabble.com/an-other-provokative-question---tf4394285.html
> sincerely
> siva
You add a new _column_ for each user?!? That is hideously broken in so
many ways. It makes the trivially easy query you are trying to write
rather complicated, prevents you from being able to use indexes for
either constraints or performance and requires you to change your table
definition anytime you add data. And that's just for starters.
Fix your table so it has three columns (id, first, last). Then your
query is as easy as:
select id,first,last from foo where last like 'J%';
Cheers,
Steve
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:46 volunteer@spatiallink.org
0 siblings, 0 replies; 70+ messages in thread
From: volunteer@spatiallink.org @ 2007-09-13 15:46 UTC (permalink / raw)
To: Alexander Staubo <alex@purefiction.net>; +Cc: pgsql-general
many apologees. right link
http://archives.postgresql.org/pgsql-general/2007-09/msg00607.php
i flip row to column if ok. but howto query??
sincerely
siva
-------- Original Message --------
Subject: Re: [GENERAL] query help
From: "Alexander Staubo" <alex@purefiction.net>
Date: Thu, September 13, 2007 11:38 am
To: "volunteer@spatiallink.org" <volunteer@spatiallink.org>
Cc: pgsql-general@postgresql.org
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> i add more column not row for new user. i want all "last like 'J%'".
> http://www.nabble.com/an-other-provokative-question---tf4394285.html
Sorry, but the only difference between your table example and your
result example was the absence, in the results, of one of the columns.
If you want to constrain by some attribute, then you have to tell us
that. I recommend that you buy a book on SQL. Lastly, I don't see what
this has to do with the "provokative question" thread.
Alexander.
---------------------------(end of broadcast)---------------------------
TIP 2: Don't 'kill -9' the postmaster
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 15:50 brian <brian@zijn-digital.com>
parent: volunteer@spatiallink.org
2 siblings, 0 replies; 70+ messages in thread
From: brian @ 2007-09-13 15:50 UTC (permalink / raw)
To: pgsql-general
volunteer@spatiallink.org wrote:
> hello
> i add more column not row for new user. i want all "last like 'J%'".
I get the feeling that the result as you've laid it out is not what we
all think it is. For example:
>>table is
>>+-------+-------+------+-------+
>>| id | one | two | three |
>>+-------+-------+------+-------+
>>| first | Jack | Jill | Mary |
>>| last | Ja | Ji | Ma |
>>+-------+-------+------+-------+
I took that to meant that you have columns 'id', 'one', two', three',
and that 'first' & 'last' are field values. However, it now seems that
'first' & 'last' are column names. If so, this makes no sense. I think
what you wanted to give us was:
+-------+-------+------+
| id | first | last |
+-------+-------+------+
| one | Jack | Ja |
| two | Jill | Ji |
| three | Mary | Ma |
result:
+-------+-------+------+
| id | first | last |
+-------+-------+------+
| one | Jack | Ja |
| two | Jill | Ji |
So, the query you want is, in fact:
SELECT * FROM your_table WHERE last LIKE ('J%');
If that's not working for you, it's perhaps because you have rows for
columns and columns for rows.
> http://www.nabble.com/an-other-provokative-question---tf4394285.html
> sincerely
> siva
>
What the heck does this have to do with anything?
Please don't top-post.
brian
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: query help
@ 2007-09-13 16:31 volunteer@spatiallink.org
0 siblings, 0 replies; 70+ messages in thread
From: volunteer@spatiallink.org @ 2007-09-13 16:31 UTC (permalink / raw)
To: pgsql-general
can u refer to row?? howto select * from table where row(#2) like 'J%'??
i wanted to test column storing but not ok as no row refer name/id.
many thank yous
sincerely
siva
-------- Original Message --------
Subject: Re: [GENERAL] query help
From: volunteer@spatiallink.org
Date: Thu, September 13, 2007 11:46 am
To: Alexander Staubo <alex@purefiction.net>
Cc: pgsql-general@postgresql.org
many apologees. right link
http://archives.postgresql.org/pgsql-general/2007-09/msg00607.php
i flip row to column if ok. but howto query??
sincerely
siva
-------- Original Message --------
Subject: Re: [GENERAL] query help
From: "Alexander Staubo" <alex@purefiction.net>
Date: Thu, September 13, 2007 11:38 am
To: "volunteer@spatiallink.org" <volunteer@spatiallink.org>
Cc: pgsql-general@postgresql.org
On 9/13/07, volunteer@spatiallink.org <volunteer@spatiallink.org> wrote:
> i add more column not row for new user. i want all "last like 'J%'".
> http://www.nabble.com/an-other-provokative-question---tf4394285.html
Sorry, but the only difference between your table example and your
result example was the absence, in the results, of one of the columns.
If you want to constrain by some attribute, then you have to tell us
that. I recommend that you buy a book on SQL. Lastly, I don't see what
this has to do with the "provokative question" thread.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2008-08-15 00:32 novice <user.postgresql@gmail.com>
0 siblings, 2 replies; 70+ messages in thread
From: novice @ 2008-08-15 00:32 UTC (permalink / raw)
To: pgsql-general
Hi,
I have a table
select id, config_id, start_day, end_day, start_time, end_time from config;
id | config_id | start_day | end_day | start_time | end_time
-----+-----------+-----------+---------+------------+----------
1 | 101 | Mon | Sun | 08:30:00 | 18:00:00
2 | 101 | Mon | Sun | 18:00:00 | 22:00:00
3 | 555 | Mon | Fri | 08:30:00 | 16:00:00
I'd like to write a query to generate the following... is it possible at all?
config_id | day | start_time | end_time
-----------+-----------+---------+-------------
101 | Mon | 08:30:00 | 18:00:00
101 | Mon | 18:00:00 | 22:00:00
101 | Tue | 08:30:00 | 18:00:00
101 | Tue | 18:00:00 | 22:00:00
101 | Wed | 08:30:00 | 18:00:00
101 | Wed | 18:00:00 | 22:00:00
101 | Thu | 08:30:00 | 18:00:00
101 | Thu | 18:00:00 | 22:00:00
101 | Fri | 08:30:00 | 18:00:00
101 | Fri | 18:00:00 | 22:00:00
101 | Sat | 08:30:00 | 18:00:00
101 | Sat | 18:00:00 | 22:00:00
101 | Sun | 08:30:00 | 18:00:00
101 | Sun | 18:00:00 | 22:00:00
555 | Mon | 08:30:00 | 18:00:00
555 | Tue | 08:30:00 | 18:00:00
555 | Wed | 08:30:00 | 18:00:00
555 | Thu | 08:30:00 | 18:00:00
555 | Fri | 08:30:00 | 18:00:00
Thanks
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2008-08-15 01:51 Hui Xie <hui.xie@axisoft.com.hk>
parent: novice <user.postgresql@gmail.com>
1 sibling, 0 replies; 70+ messages in thread
From: Hui Xie @ 2008-08-15 01:51 UTC (permalink / raw)
To: novice <user.postgresql@gmail.com>; +Cc: pgsql-general; pgsql-general-owner@postgresql.org
Hi ,
below can work?
select config_id, start_day as day, start_time, end_time from config
union
select config_id, end_day as day, start_time, end_time from config
Best Regards,
Hui Xie
-------------------------------------------
Axisoft Co. Ltd. Zhuhai Branch
Tel: (86) 0756-3612121 8858
novice <user.postgresql@gmail.com>
Sent by: pgsql-general-owner@postgresql.org
15/08/2008 08:32 AM
To
pgsql-general@postgresql.org
cc
Subject
[GENERAL] Query help
Hi,
I have a table
select id, config_id, start_day, end_day, start_time, end_time from
config;
id | config_id | start_day | end_day | start_time | end_time
-----+-----------+-----------+---------+------------+----------
1 | 101 | Mon | Sun | 08:30:00 | 18:00:00
2 | 101 | Mon | Sun | 18:00:00 | 22:00:00
3 | 555 | Mon | Fri | 08:30:00 | 16:00:00
I'd like to write a query to generate the following... is it possible at
all?
config_id | day | start_time | end_time
-----------+-----------+---------+-------------
101 | Mon | 08:30:00 | 18:00:00
101 | Mon | 18:00:00 | 22:00:00
101 | Tue | 08:30:00 | 18:00:00
101 | Tue | 18:00:00 | 22:00:00
101 | Wed | 08:30:00 | 18:00:00
101 | Wed | 18:00:00 | 22:00:00
101 | Thu | 08:30:00 | 18:00:00
101 | Thu | 18:00:00 | 22:00:00
101 | Fri | 08:30:00 | 18:00:00
101 | Fri | 18:00:00 | 22:00:00
101 | Sat | 08:30:00 | 18:00:00
101 | Sat | 18:00:00 | 22:00:00
101 | Sun | 08:30:00 | 18:00:00
101 | Sun | 18:00:00 | 22:00:00
555 | Mon | 08:30:00 | 18:00:00
555 | Tue | 08:30:00 | 18:00:00
555 | Wed | 08:30:00 | 18:00:00
555 | Thu | 08:30:00 | 18:00:00
555 | Fri | 08:30:00 | 18:00:00
Thanks
--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general
*** The email has been scanned by AxiScan ***
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2008-08-15 03:46 novice <user.postgresql@gmail.com>
parent: novice <user.postgresql@gmail.com>
1 sibling, 0 replies; 70+ messages in thread
From: novice @ 2008-08-15 03:46 UTC (permalink / raw)
To: pgsql-general
2008/8/15 novice <user.postgresql@gmail.com>:
> Hi,
> I have a table
>
> select id, config_id, start_day, end_day, start_time, end_time from config;
>
> id | config_id | start_day | end_day | start_time | end_time
> -----+-----------+-----------+---------+------------+----------
> 1 | 101 | Mon | Sun | 08:30:00 | 18:00:00
> 2 | 101 | Mon | Sun | 18:00:00 | 22:00:00
> 3 | 555 | Mon | Fri | 08:30:00 | 16:00:00
>
>
>
> I'd like to write a query to generate the following... is it possible at all?
>
> config_id | day | start_time | end_time
> -----------+-----------+---------+-------------
> 101 | Mon | 08:30:00 | 18:00:00
> 101 | Mon | 18:00:00 | 22:00:00
> 101 | Tue | 08:30:00 | 18:00:00
> 101 | Tue | 18:00:00 | 22:00:00
> 101 | Wed | 08:30:00 | 18:00:00
> 101 | Wed | 18:00:00 | 22:00:00
> 101 | Thu | 08:30:00 | 18:00:00
> 101 | Thu | 18:00:00 | 22:00:00
> 101 | Fri | 08:30:00 | 18:00:00
> 101 | Fri | 18:00:00 | 22:00:00
> 101 | Sat | 08:30:00 | 18:00:00
> 101 | Sat | 18:00:00 | 22:00:00
> 101 | Sun | 08:30:00 | 18:00:00
> 101 | Sun | 18:00:00 | 22:00:00
> 555 | Mon | 08:30:00 | 18:00:00
> 555 | Tue | 08:30:00 | 18:00:00
> 555 | Wed | 08:30:00 | 18:00:00
> 555 | Thu | 08:30:00 | 18:00:00
> 555 | Fri | 08:30:00 | 18:00:00
>
> Thanks
>
Solved:
create TABLE weekday
(
wd varchar(3),
seq int
)
INSERT INTO weekday (wd, seq) VALUES
('Mon', '1'),
('Tue', '2'),
('Wed', '3'),
('Thu', '4'),
('Fri', '5'),
('Sat', '6'),
('Sun', '7');
SELECT config.config_id, w.wd, config.start_time, config.end_time
FROM config
INNER JOIN weekday s ON config.start_day = s.wd
INNER JOIN weekday e ON config.end_day = e.wd
CROSS JOIN weekday w
WHERE w.seq >= s.seq
AND w.seq <= e.seq
ORDER BY config.config_id, w.seq, w.wd
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2008-08-15 04:12 Brent Wood <b.wood@niwa.co.nz>
0 siblings, 0 replies; 70+ messages in thread
From: Brent Wood @ 2008-08-15 04:12 UTC (permalink / raw)
To: user.postgresql@gmail.com; +Cc: pgsql-general
If I read this correctly, you want the output sorted by config_id,start_day(day),start_time,
thus:
select config_id, start_day as day, start_time, end_time from config
order by config_id, start_day, start_time;
Cheers,
Brent Wood
>>> novice <user.postgresql@gmail.com> 08/15/08 3:55 PM >>>
Hi,
I have a table
select id, config_id, start_day, end_day, start_time, end_time from config;
id | config_id | start_day | end_day | start_time | end_time
-----+-----------+-----------+---------+------------+----------
1 | 101 | Mon | Sun | 08:30:00 | 18:00:00
2 | 101 | Mon | Sun | 18:00:00 | 22:00:00
3 | 555 | Mon | Fri | 08:30:00 | 16:00:00
I'd like to write a query to generate the following... is it possible at all?
config_id | day | start_time | end_time
-----------+-----------+---------+-------------
101 | Mon | 08:30:00 | 18:00:00
101 | Mon | 18:00:00 | 22:00:00
101 | Tue | 08:30:00 | 18:00:00
101 | Tue | 18:00:00 | 22:00:00
101 | Wed | 08:30:00 | 18:00:00
101 | Wed | 18:00:00 | 22:00:00
101 | Thu | 08:30:00 | 18:00:00
101 | Thu | 18:00:00 | 22:00:00
101 | Fri | 08:30:00 | 18:00:00
101 | Fri | 18:00:00 | 22:00:00
101 | Sat | 08:30:00 | 18:00:00
101 | Sat | 18:00:00 | 22:00:00
101 | Sun | 08:30:00 | 18:00:00
101 | Sun | 18:00:00 | 22:00:00
555 | Mon | 08:30:00 | 18:00:00
555 | Tue | 08:30:00 | 18:00:00
555 | Wed | 08:30:00 | 18:00:00
555 | Thu | 08:30:00 | 18:00:00
555 | Fri | 08:30:00 | 18:00:00
Thanks
--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2016-10-05 03:31 Bret Stern <bret_stern@machinemanagement.com>
0 siblings, 2 replies; 70+ messages in thread
From: Bret Stern @ 2016-10-05 03:31 UTC (permalink / raw)
To: pgsql-general
Good evening,
I'm curious about a way to ask the following question of my vendors
table.
psuedo1 "select all vendors which exist in BUR and EBC and SNJ"
and
psuedo2 "select all vendors which DO NOT exist in all three show rooms
The data is from a Sage accounting system which I pull out and place in
a
pg db. What we are trying to do is identify which vendors are defined in
all three of our showrooms, and vice-versa, which ones are not.
ap_vendors table
company_code character varying(10) NOT NULL,
ap_division_no character varying(2) NOT NULL,
vendor_no character varying(7) NOT NULL,
terms_code character varying(2),
vendor_name character varying(30),
address_line1 character varying(30),
address_line2 character varying(30),
address_line3 character varying(30),
city character varying(20),
state character varying(2),
zip_code character varying(10),
telephone_no character varying(17),
fax_no character varying(17),
CONSTRAINT ap_vendors_pk PRIMARY KEY (company_code, ap_division_no,
vendor_no)
sample records:
"BUR";"00";"ADEXU";"30";"ADEX
USA";"''";"''";"''";"''";"''";"92831";"''";"''"
"BUR";"00";"AGORA";"30";"Agora Natural
Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
"BUR";"00";"AKDOP";"30";"AKDO
Pacific";"''";"''";"''";"''";"''";"94545";"''";"''"
"EBC";"00";"ADEXU";"30";"ADEX
USA";"''";"''";"''";"''";"''";"92831";"''";"''"
"EBC";"00";"AGORA";"30";"Agora Natural
Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
"EBC";"00";"ARIZ01";"30";"Arizona
Tile";"''";"''";"''";"''";"''";"94550";"''";"''"
"SNJ";"00";"AKDOP";"30";"AKDO
Pacific";"''";"''";"''";"''";"''";"94545";"''";"''"
"SNJ";"00";"AGORA";"30";"Agora Natural
Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
"SNJ";"00";"ADEXU";"30";"ADEX
USA";"''";"''";"''";"''";"''";"92831";"''";"''"
What I need is a query which I can modify to return only vendors which
exists
in all three company_code columns ( BUR, EBC, SNJ) (they represent
showroom location)
eg; exists in BUR, EBC, SNJ
ADEXU
AGORA
OR
modify the query to return only the vendors which DO NOT exist in all
three showrooms based on the first column company_code
eg;
AKDOP only exists in BUR and SNJ
ARIZ01 only exists in EBC
Thanks
Bret
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2016-10-05 03:35 Rob Sargent <robjsargent@gmail.com>
parent: Bret Stern <bret_stern@machinemanagement.com>
1 sibling, 0 replies; 70+ messages in thread
From: Rob Sargent @ 2016-10-05 03:35 UTC (permalink / raw)
To: bret_stern@machinemanagement.com; +Cc: pgsql-general
> On Oct 4, 2016, at 9:31 PM, Bret Stern <bret_stern@machinemanagement.com> wrote:
>
> Good evening,
> I'm curious about a way to ask the following question of my vendors
> table.
>
> psuedo1 "select all vendors which exist in BUR and EBC and SNJ"
>
> and
> psuedo2 "select all vendors which DO NOT exist in all three show rooms
>
>
> The data is from a Sage accounting system which I pull out and place in a
> pg db. What we are trying to do is identify which vendors are defined in
> all three of our showrooms, and vice-versa, which ones are not.
>
> ap_vendors table
> company_code character varying(10) NOT NULL,
> ap_division_no character varying(2) NOT NULL,
> vendor_no character varying(7) NOT NULL,
> terms_code character varying(2),
> vendor_name character varying(30),
> address_line1 character varying(30),
> address_line2 character varying(30),
> address_line3 character varying(30),
> city character varying(20),
> state character varying(2),
> zip_code character varying(10),
> telephone_no character varying(17),
> fax_no character varying(17),
> CONSTRAINT ap_vendors_pk PRIMARY KEY (company_code, ap_division_no, vendor_no)
>
> sample records:
> "BUR";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";"92831";"''";"''"
> "BUR";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
> "BUR";"00";"AKDOP";"30";"AKDO Pacific";"''";"''";"''";"''";"''";"94545";"''";"''"
> "EBC";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";"92831";"''";"''"
> "EBC";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
> "EBC";"00";"ARIZ01";"30";"Arizona Tile";"''";"''";"''";"''";"''";"94550";"''";"''"
> "SNJ";"00";"AKDOP";"30";"AKDO Pacific";"''";"''";"''";"''";"''";"94545";"''";"''"
> "SNJ";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";"''";"90248";"''";"''"
> "SNJ";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";"92831";"''";"''"
>
> What I need is a query which I can modify to return only vendors which exists
> in all three company_code columns ( BUR, EBC, SNJ) (they represent showroom location)
>
> eg; exists in BUR, EBC, SNJ
> ADEXU
> AGORA
>
> OR
>
> modify the query to return only the vendors which DO NOT exist in all
> three showrooms based on the first column company_code
>
> eg;
> AKDOP only exists in BUR and SNJ
> ARIZ01 only exists in EBC
>
> Thanks
> Bret
>
>
Not sure I like the schema but
select vendor_no, count(*) from ap_vendors having count(*) = 3;
and maybe count(*) < 3 is your second answer.
--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2016-10-05 03:55 Daniel Caldeweyher <dcalde@gmail.com>
parent: Bret Stern <bret_stern@machinemanagement.com>
1 sibling, 0 replies; 70+ messages in thread
From: Daniel Caldeweyher @ 2016-10-05 03:55 UTC (permalink / raw)
To: bret_stern@machinemanagement.com; +Cc: pgsql-general
Try this:
select distinct vendor_no, vendor_name
from ap_vendors
where vendor_no in (
select vendor_no from ap_vendors
group by vendor_no
having array_agg(company_code) @> ARRAY['BUR','EBC','SNJ'])
On Wed, Oct 5, 2016 at 1:31 PM, Bret Stern <bret_stern@machinemanagement.com
> wrote:
> Good evening,
> I'm curious about a way to ask the following question of my vendors
> table.
>
> psuedo1 "select all vendors which exist in BUR and EBC and SNJ"
>
> and
> psuedo2 "select all vendors which DO NOT exist in all three show rooms
>
>
> The data is from a Sage accounting system which I pull out and place in a
> pg db. What we are trying to do is identify which vendors are defined in
> all three of our showrooms, and vice-versa, which ones are not.
>
> ap_vendors table
> company_code character varying(10) NOT NULL,
> ap_division_no character varying(2) NOT NULL,
> vendor_no character varying(7) NOT NULL,
> terms_code character varying(2),
> vendor_name character varying(30),
> address_line1 character varying(30),
> address_line2 character varying(30),
> address_line3 character varying(30),
> city character varying(20),
> state character varying(2),
> zip_code character varying(10),
> telephone_no character varying(17),
> fax_no character varying(17),
> CONSTRAINT ap_vendors_pk PRIMARY KEY (company_code, ap_division_no,
> vendor_no)
>
> sample records:
> "BUR";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";
> "92831";"''";"''"
> "BUR";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";
> "''";"90248";"''";"''"
> "BUR";"00";"AKDOP";"30";"AKDO Pacific";"''";"''";"''";"''";"
> ''";"94545";"''";"''"
> "EBC";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";
> "92831";"''";"''"
> "EBC";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";
> "''";"90248";"''";"''"
> "EBC";"00";"ARIZ01";"30";"Arizona Tile";"''";"''";"''";"''";"''"
> ;"94550";"''";"''"
> "SNJ";"00";"AKDOP";"30";"AKDO Pacific";"''";"''";"''";"''";"
> ''";"94545";"''";"''"
> "SNJ";"00";"AGORA";"30";"Agora Natural Surfaces";"''";"''";"''";"''";
> "''";"90248";"''";"''"
> "SNJ";"00";"ADEXU";"30";"ADEX USA";"''";"''";"''";"''";"''";
> "92831";"''";"''"
>
> What I need is a query which I can modify to return only vendors which
> exists
> in all three company_code columns ( BUR, EBC, SNJ) (they represent
> showroom location)
>
> eg; exists in BUR, EBC, SNJ
> ADEXU
> AGORA
>
> OR
>
> modify the query to return only the vendors which DO NOT exist in all
> three showrooms based on the first column company_code
>
> eg;
> AKDOP only exists in BUR and SNJ
> ARIZ01 only exists in EBC
>
> Thanks
> Bret
>
>
>
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2019-01-01 19:05 Chuck Martin <clmartin@theombudsman.com>
0 siblings, 4 replies; 70+ messages in thread
From: Chuck Martin @ 2019-01-01 19:05 UTC (permalink / raw)
To: pgsql-general
Sorry if this is too basic a question for this list, but I don't fully get
how to use aggregates (sum()) and group-by together. I'm trying to get a
list of transactions where the total for a given account exceeds a given
number. I'm not sure an example is needed, but if so, consider this
simplified data:
accountid. name
1 bill
2. james
3 sarah
4 carl
transaction
id. amount. accountid. name
1. 50. 1 bill
2. 25. 2 james
3 35 4 carl
4. 75. 1 bill
5 25. 1 bill
6 50 3 sarah
results wanted-all transactions where account total >= 50
id. amount. accountid. name
1. 50. 1 bill
3. 75. 1 bill
4 25. 1 bill
5 50 3 sarah
I've tried to understand how to use GROUP BY and HAVING, but the penny
won't drop. I keep getting errors saying that all columns in the SELECT
have to also be in the GROUP BY, but nothing I've done seems to produce the
correct results. I think because the GROUP BY contains multiple columns, so
each row is treated as a group. It also is difficult to parse out since in
the real world, many more tables and columns are involved.
Chuck Martin
Avondale Software
^ permalink raw reply [nested|flat] 70+ messages in thread
* RE: Query help
@ 2019-01-01 19:14 Scot Kreienkamp <Scot.Kreienkamp@la-z-boy.com>
parent: Chuck Martin <clmartin@theombudsman.com>
3 siblings, 0 replies; 70+ messages in thread
From: Scot Kreienkamp @ 2019-01-01 19:14 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; pgsql-general
Any columns that aren’t involved in a summary operation (think math type or some other type of summary operation) have to be in the group by statement.
From what you show below, I would try something like this (untested):
Select accountid,name,sum(amount) from table where sum(amount) >’50’ group by accountid,name sort by accountid,name;
You can’t show the transaction ID unless you have duplicate transaction ID’s that you wanted to group by. If you did try to show it you’d get the entire table. Or you could use a more advanced query to gather the multiple transaction ID’s into a single record for the query results which would let the sum and group by work.
Scot Kreienkamp |Senior Systems Engineer | La-Z-Boy Corporate
One La-Z-Boy Drive| Monroe, Michigan 48162 | Office: 734-384-6403 | | Mobile: 7349151444 | Email: Scot.Kreienkamp@la-z-boy.com
From: Chuck Martin [mailto:clmartin@theombudsman.com]
Sent: Tuesday, January 01, 2019 2:06 PM
To: pgsql-general <pgsql-general@postgresql.org>
Subject: Query help
Sorry if this is too basic a question for this list, but I don't fully get how to use aggregates (sum()) and group-by together. I'm trying to get a list of transactions where the total for a given account exceeds a given number. I'm not sure an example is needed, but if so, consider this simplified data:
accountid. name
1 bill
2. james
3 sarah
4 carl
transaction
id. amount. accountid. name
1. 50. 1 bill
2. 25. 2 james
3 35 4 carl
4. 75. 1 bill
5 25. 1 bill
6 50 3 sarah
results wanted-all transactions where account total >= 50
id. amount. accountid. name
1. 50. 1 bill
3. 75. 1 bill
4 25. 1 bill
5 50 3 sarah
I've tried to understand how to use GROUP BY and HAVING, but the penny won't drop. I keep getting errors saying that all columns in the SELECT have to also be in the GROUP BY, but nothing I've done seems to produce the correct results. I think because the GROUP BY contains multiple columns, so each row is treated as a group. It also is difficult to parse out since in the real world, many more tables and columns are involved.
Chuck Martin
Avondale Software
This message is intended only for the individual or entity to which it is addressed. It may contain privileged, confidential information which is exempt from disclosure under applicable laws. If you are not the intended recipient, you are strictly prohibited from disseminating or distributing this information (other than to the intended recipient) or copying this information. If you have received this communication in error, please notify us immediately by e-mail or by telephone at the above number. Thank you.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 19:26 John W Higgins <wishdev@gmail.com>
parent: Chuck Martin <clmartin@theombudsman.com>
3 siblings, 1 reply; 70+ messages in thread
From: John W Higgins @ 2019-01-01 19:26 UTC (permalink / raw)
To: pgsql-general
On Tue, Jan 1, 2019 at 11:06 AM Chuck Martin <clmartin@theombudsman.com>
wrote:
> Sorry if this is too basic a question for this list, but I don't fully get
> how to use aggregates (sum()) and group-by together. I'm trying to get a
> list of transactions where the total for a given account exceeds a given
> number. I'm not sure an example is needed, but if so, consider this
> simplified data:
>
> accountid. name
> 1 bill
> 2. james
> 3 sarah
> 4 carl
>
> transaction
> id. amount. accountid. name
> 1. 50. 1 bill
> 2. 25. 2 james
> 3 35 4 carl
> 4. 75. 1 bill
> 5 25. 1 bill
> 6 50 3 sarah
>
> results wanted-all transactions where account total >= 50
>
> id. amount. accountid. name
> 1. 50. 1 bill
> 3. 75. 1 bill
> 4 25. 1 bill
> 5 50 3 sarah
>
>
You have 2 concepts here - identify the accounts with a total over 50 and
then show the transactions for those accounts. I prefer CTEs here because
they allow for better understanding (to me) of the steps involved. A
subquery would work here as well.
with accounts_over_total as (
select accountid from transactions where sum(amount) >= 50 group by
accountid)
select transactions.* from transactions join accounts_over_total on
transactions.accountid = accounts.accountid
John
> I've tried to understand how to use GROUP BY and HAVING, but the penny
> won't drop. I keep getting errors saying that all columns in the SELECT
> have to also be in the GROUP BY, but nothing I've done seems to produce the
> correct results. I think because the GROUP BY contains multiple columns, so
> each row is treated as a group. It also is difficult to parse out since in
> the real world, many more tables and columns are involved.
>
> Chuck Martin
> Avondale Software
>
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2019-01-01 19:28 David G. Johnston <david.g.johnston@gmail.com>
parent: Chuck Martin <clmartin@theombudsman.com>
3 siblings, 1 reply; 70+ messages in thread
From: David G. Johnston @ 2019-01-01 19:28 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; +Cc: pgsql-general
On Tuesday, January 1, 2019, Chuck Martin <clmartin@theombudsman.com> wrote:
> results wanted-all transactions where account total >= 50
>
> id. amount. accountid. name
> 1. 50. 1 bill
> 3. 75. 1 bill
> 4 25. 1 bill
> 5 50 3 sarah
>
This result does not require group by, just the where clause you’ve noted
above.
David J.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 19:29 David G. Johnston <david.g.johnston@gmail.com>
parent: David G. Johnston <david.g.johnston@gmail.com>
0 siblings, 0 replies; 70+ messages in thread
From: David G. Johnston @ 2019-01-01 19:29 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; +Cc: pgsql-general
On Tuesday, January 1, 2019, David G. Johnston <david.g.johnston@gmail.com>
wrote:
> On Tuesday, January 1, 2019, Chuck Martin <clmartin@theombudsman.com>
> wrote:
>
>> results wanted-all transactions where account total >= 50
>>
>> id. amount. accountid. name
>> 1. 50. 1 bill
>> 3. 75. 1 bill
>> 4 25. 1 bill
>> 5 50 3 sarah
>>
>
> This result does not require group by, just the where clause you’ve noted
> above.
>
>
Never mind...missed how the 25 got included
David J.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 19:40 Adrian Klaver <adrian.klaver@aklaver.com>
parent: Chuck Martin <clmartin@theombudsman.com>
3 siblings, 0 replies; 70+ messages in thread
From: Adrian Klaver @ 2019-01-01 19:40 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; pgsql-general
On 1/1/19 11:05 AM, Chuck Martin wrote:
> Sorry if this is too basic a question for this list, but I don't fully
> get how to use aggregates (sum()) and group-by together. I'm trying to
> get a list of transactions where the total for a given account exceeds a
> given number. I'm not sure an example is needed, but if so, consider
> this simplified data:
>
> accountid. name
> 1 bill
> 2. james
> 3 sarah
> 4 carl
>
> transaction
> id. amount. accountid. name
> 1. 50. 1 bill
> 2. 25. 2 james
> 3 35 4 carl
> 4. 75. 1 bill
> 5 25. 1 bill
> 6 50 3 sarah
>
> results wanted-all transactions where account total >= 50
>
> id. amount. accountid. name
> 1. 50. 1 bill
> 3. 75. 1 bill
> 4 25. 1 bill
> 5 50 3 sarah
>
> I've tried to understand how to use GROUP BY and HAVING, but the penny
> won't drop. I keep getting errors saying that all columns in the SELECT
> have to also be in the GROUP BY, but nothing I've done seems to produce
> the correct results. I think because the GROUP BY contains multiple
> columns, so each row is treated as a group. It also is difficult to
> parse out since in the real world, many more tables and columns are
> involved.
Window Functions?:
https://www.postgresql.org/docs/11/tutorial-window.html
Or do something like(untested):
select transactionid, amount, accountid, name from transaction join
(select accountid, sum(amount) from transaction group by(accountid)) as
account_sum on transaction.transactionid = account_sum.accountid and
account_sum.sum >= 50
>
> Chuck Martin
> Avondale Software
--
Adrian Klaver
adrian.klaver@aklaver.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 19:44 Adrian Klaver <adrian.klaver@aklaver.com>
parent: John W Higgins <wishdev@gmail.com>
0 siblings, 1 reply; 70+ messages in thread
From: Adrian Klaver @ 2019-01-01 19:44 UTC (permalink / raw)
To: John W Higgins <wishdev@gmail.com>; pgsql-general
On 1/1/19 11:26 AM, John W Higgins wrote:
> On Tue, Jan 1, 2019 at 11:06 AM Chuck Martin <clmartin@theombudsman.com
> <mailto:clmartin@theombudsman.com>> wrote:
>
> Sorry if this is too basic a question for this list, but I don't
> fully get how to use aggregates (sum()) and group-by together. I'm
> trying to get a list of transactions where the total for a given
> account exceeds a given number. I'm not sure an example is needed,
> but if so, consider this simplified data:
>
> accountid. name
> 1 bill
> 2. james
> 3 sarah
> 4 carl
>
> transaction
> id. amount. accountid. name
> 1. 50. 1 bill
> 2. 25. 2 james
> 3 35 4 carl
> 4. 75. 1 bill
> 5 25. 1 bill
> 6 50 3 sarah
>
> results wanted-all transactions where account total >= 50
>
> id. amount. accountid. name
> 1. 50. 1 bill
> 3. 75. 1 bill
> 4 25. 1 bill
> 5 50 3 sarah
>
>
> You have 2 concepts here - identify the accounts with a total over 50
> and then show the transactions for those accounts. I prefer CTEs here
> because they allow for better understanding (to me) of the steps
> involved. A subquery would work here as well.
>
> with accounts_over_total as (
> select accountid from transactions where sum(amount) >= 50 group by
> accountid)
Unfortunately there is a hitch in the above:(
select p_item_no from projection where sum(qty) > 100 group
by(p_item_no);
ERROR: aggregate functions are not allowed in WHERE
LINE 1: select p_item_no, sum(qty) from projection where sum(qty) >
> select transactions.* from transactions join accounts_over_total on
> transactions.accountid = accounts.accountid
>
> John
>
> I've tried to understand how to use GROUP BY and HAVING, but the
> penny won't drop. I keep getting errors saying that all columns in
> the SELECT have to also be in the GROUP BY, but nothing I've done
> seems to produce the correct results. I think because the GROUP BY
> contains multiple columns, so each row is treated as a group. It
> also is difficult to parse out since in the real world, many more
> tables and columns are involved.
>
> Chuck Martin
> Avondale Software
>
--
Adrian Klaver
adrian.klaver@aklaver.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 20:05 David G. Johnston <david.g.johnston@gmail.com>
parent: Adrian Klaver <adrian.klaver@aklaver.com>
0 siblings, 1 reply; 70+ messages in thread
From: David G. Johnston @ 2019-01-01 20:05 UTC (permalink / raw)
To: Adrian Klaver <adrian.klaver@aklaver.com>; +Cc: John W Higgins <wishdev@gmail.com>; pgsql-general
On Tuesday, January 1, 2019, Adrian Klaver <adrian.klaver@aklaver.com>
wrote:
> On 1/1/19 11:26 AM, John W Higgins wrote:
>>
>> with accounts_over_total as (
>> select accountid from transactions where sum(amount) >= 50 group by
>> accountid)
>>
>
> Unfortunately there is a hitch in the above:(
>
> select p_item_no from projection where sum(qty) > 100 group by(p_item_no);
> ERROR: aggregate functions are not allowed in WHERE
>
Which is where the HAVING clause comes in. It filters out groups based on
an expression containing an aggregate function.
David J.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-01 22:10 Adrian Klaver <adrian.klaver@aklaver.com>
parent: David G. Johnston <david.g.johnston@gmail.com>
0 siblings, 0 replies; 70+ messages in thread
From: Adrian Klaver @ 2019-01-01 22:10 UTC (permalink / raw)
To: David G. Johnston <david.g.johnston@gmail.com>; +Cc: John W Higgins <wishdev@gmail.com>; pgsql-general
On 1/1/19 12:05 PM, David G. Johnston wrote:
> On Tuesday, January 1, 2019, Adrian Klaver <adrian.klaver@aklaver.com
> <mailto:adrian.klaver@aklaver.com>> wrote:
>
> On 1/1/19 11:26 AM, John W Higgins wrote:
>
> with accounts_over_total as (
> select accountid from transactions where sum(amount) >= 50 group
> by accountid)
>
>
> Unfortunately there is a hitch in the above:(
>
> select p_item_no from projection where sum(qty) > 100 group
> by(p_item_no);
> ERROR: aggregate functions are not allowed in WHERE
>
>
> Which is where the HAVING clause comes in. It filters out groups based
> on an expression containing an aggregate function.
Hmm, guess I should spend more time reading the SELECT docs:)
>
> David J.
--
Adrian Klaver
adrian.klaver@aklaver.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Query help
@ 2019-01-26 23:04 Chuck Martin <clmartin@theombudsman.com>
0 siblings, 3 replies; 70+ messages in thread
From: Chuck Martin @ 2019-01-26 23:04 UTC (permalink / raw)
To: pgsql-general
I'm having trouble formulating a query. This is a simplified version of the
tables:
ombcase
------------
case_pkey integer, primary key
casename varchar
insdatetime timestamp w/o time zone
status_fkey integer, foreign key
status
--------
status_pkey integer, primary key
statusid varchar
statuschange
--------
statuschange_pkey integer, primary key
insdatetime timestamp w/o time zone
ombcase_fkey integer, foreign key
oldstatus_fkey integer, foreign key
newstatus_fkey integer, foreign key
active integer, not nullable
The idea should be obvious, but to explain, insdatetime is set when a new
record is created in any table. All records in ombcase have a foreign key
to status that can't be null. When status changes, a record is created in
statuschange recording the old and new status keys, and the time (etc).
The goal is to find records in ombcase that have not had a status change in
xx days. If the status has not changed, there will be no statuschange
record.
This query returns the age of each ombcase and the last statuschange
record, but only if there is a statuschange record:
--Finds the age and last status change for open cases, but not age of cases
with no status change
SELECT casename, age(ombcase.insdatetime) AS caseage,
age(laststatuschange.created_at) AS statusage
FROM
(SELECT
case_fkey, MAX(insdatetime) AS created_at
FROM
statuschange
GROUP BY
case_fkey) AS laststatuschange
INNER JOIN
ombcase
ON
laststatuschange.case_fkey = case_pkey
RIGHT JOIN status
ON status_fkey = status_pkey
WHERE lower(statusid) NOT LIKE ('closed%')
AND case_pkey <> 0
I want to use coalesce
(age(ombcase.insdatetime),age(statuschange.insdatetime) ) to return the
time that a case has been in a status—or without a status change. But first
I have to find the cases with no statuschange record. I was able to do
that, too, using this query:
--find cases in status too long
SELECT casename, coalesce
(age(ombcase.insdatetime),age(statuschange.insdatetime) )
FROM ombcase
LEFT JOIN statuschange
ON case_fkey = case_pkey
LEFT JOIN status
ON status_fkey = status_pkey
AND lower(statusid) NOT LIKE ('closed%')
AND coalesce ( age(ombcase.insdatetime), age(statuschange.insdatetime) ) >
'2 months'
But this query will return all statuschange records for an ombcase record
that has multiple ones.
Any suggestions on how to combine the two ideas?
Chuck Martin
Avondale Software
--
Chuck Martin
Avondale Software
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-26 23:30 Ron <ronljohnsonjr@gmail.com>
parent: Chuck Martin <clmartin@theombudsman.com>
2 siblings, 1 reply; 70+ messages in thread
From: Ron @ 2019-01-26 23:30 UTC (permalink / raw)
To: pgsql-general@lists.postgresql.org
On 1/26/19 5:04 PM, Chuck Martin wrote:
> I'm having trouble formulating a query. This is a simplified version of
> the tables:
>
> ombcase
> ------------
> case_pkey integer, primary key
> casename varchar
> insdatetime timestamp w/o time zone
> status_fkey integer, foreign key
>
> status
> --------
> status_pkey integer, primary key
> statusid varchar
>
> statuschange
> --------
> statuschange_pkey integer, primary key
> insdatetime timestamp w/o time zone
> ombcase_fkey integer, foreign key
> oldstatus_fkey integer, foreign key
> newstatus_fkey integer, foreign key
> active integer, not nullable
>
> The idea should be obvious, but to explain, insdatetime is set when a new
> record is created in any table. All records in ombcase have a foreign key
> to status that can't be null. When status changes, a record is created in
> statuschange recording the old and new status keys, and the time (etc).
>
> The goal is to find records in ombcase that have not had a status change
> in xx days. If the status has not changed, there will be no statuschange
> record.
Does statuschange.*ins*datetime record when an ombcase record was first
inserted, or when the status_fkey associated with ombcase.case_pkey was updated?
And why not add upddatetime to ombcase? That would solve all your problems.
--
Angular momentum makes the world go 'round.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 02:38 Charles Martin <ssappeals@gmail.com>
parent: Ron <ronljohnsonjr@gmail.com>
0 siblings, 0 replies; 70+ messages in thread
From: Charles Martin @ 2019-01-27 02:38 UTC (permalink / raw)
To: Ron <ronljohnsonjr@gmail.com>; +Cc: pgsql-general@lists.postgresql.org
On Sat, Jan 26, 2019 at 6:30 PM Ron <ronljohnsonjr@gmail.com> wrote:
> On 1/26/19 5:04 PM, Chuck Martin wrote:
>
> I'm having trouble formulating a query. This is a simplified version of
> the tables:
>
> ombcase
> ------------
> case_pkey integer, primary key
> casename varchar
> insdatetime timestamp w/o time zone
> status_fkey integer, foreign key
>
> status
> --------
> status_pkey integer, primary key
> statusid varchar
>
> statuschange
> --------
> statuschange_pkey integer, primary key
> insdatetime timestamp w/o time zone
> ombcase_fkey integer, foreign key
> oldstatus_fkey integer, foreign key
> newstatus_fkey integer, foreign key
> active integer, not nullable
>
> The idea should be obvious, but to explain, insdatetime is set when a new
> record is created in any table. All records in ombcase have a foreign key
> to status that can't be null. When status changes, a record is created in
> statuschange recording the old and new status keys, and the time (etc).
>
> The goal is to find records in ombcase that have not had a status change
> in xx days. If the status has not changed, there will be no statuschange
> record.
>
>
> Does statuschange.*ins*datetime record when an ombcase record was first
> inserted, or when the status_fkey associated with ombcase.case_pkey was
> updated?
>
No, it only creates a statuschange record when the status is first changed,
not when the ombcase record is created.
>
>
> And why not add upddatetime to ombcase? That would solve all your
> problems.
>
I do record the time of the last update, but that could reflect a change of
any column (most I didn’t list).
>
>
> --
> Angular momentum makes the world go 'round.
>
--
Charles L. Martin
Martin Jones & Piemonte
BUSINESS email: service@martinandjones.us
Personal email: clmartin@ssappeals.com
Decatur Office:
123 N. McDonough St.
Decatur, GA 30030
404-373-3116
Fax 404-373-4110
Charlotte Office:
4601 Charlotte Park Drive, Suite 390
Charlotte, NC 28217
704-399-8890
Fax 888-490-1315
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 13:07 Peter J. Holzer <hjp-pgsql@hjp.at>
parent: Chuck Martin <clmartin@theombudsman.com>
2 siblings, 1 reply; 70+ messages in thread
From: Peter J. Holzer @ 2019-01-27 13:07 UTC (permalink / raw)
To: pgsql-general@lists.postgresql.org
On 2019-01-26 18:04:23 -0500, Chuck Martin wrote:
> I'm having trouble formulating a query. This is a simplified version of the
> tables:
>
> ombcase
> ------------
> case_pkey integer, primary key
> casename varchar
> insdatetime timestamp w/o time zone
> status_fkey integer, foreign key
>
> status
> --------
> status_pkey integer, primary key
> statusid varchar
>
> statuschange
> --------
> statuschange_pkey integer, primary key
> insdatetime timestamp w/o time zone
> ombcase_fkey integer, foreign key
> oldstatus_fkey integer, foreign key
> newstatus_fkey integer, foreign key
> active integer, not nullable
>
> The idea should be obvious, but to explain, insdatetime is set when a new
> record is created in any table. All records in ombcase have a foreign key to
> status that can't be null. When status changes, a record is created in
> statuschange recording the old and new status keys, and the time (etc).
>
> The goal is to find records in ombcase that have not had a status change in xx
> days. If the status has not changed, there will be no statuschange record.
The easiest way is to use set operations:
select case_pkey from ombcase;
gives you all the ombcase ids.
select ombcase_fkey from statuschange where insdatetime >= now()::date - xx;
gives you all ombcase ids which had a status change in the last xx days.
Therefore,
select case_pkey from ombcase
except
select ombcase_fkey from statuschange where insdatetime >= now()::date - xx;
gives you all ombcase ids which did /not/ have a status change in the
last xx days.
Another way would be to use a CTE
(https://www.postgresql.org/docs/10/queries-with.html) to extract the
last status change for each ombcase and then do a left join of ombcase
to that CTE.
hp
--
_ | Peter J. Holzer | we build much bigger, better disasters now
|_|_) | | because we have much more sophisticated
| | | hjp@hjp.at | management tools.
__/ | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/;
Attachments:
signature.asc (application/pgp-signature, 832B) download
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 19:55 Adrian Klaver <adrian.klaver@aklaver.com>
parent: Chuck Martin <clmartin@theombudsman.com>
2 siblings, 1 reply; 70+ messages in thread
From: Adrian Klaver @ 2019-01-27 19:55 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; pgsql-general
On 1/26/19 3:04 PM, Chuck Martin wrote:
> I'm having trouble formulating a query. This is a simplified version of
> the tables:
>
> ombcase
> ------------
> case_pkey integer, primary key
> casename varchar
> insdatetime timestamp w/o time zone
> status_fkey integer, foreign key
>
> status
> --------
> status_pkey integer, primary key
> statusid varchar
>
> statuschange
> --------
> statuschange_pkey integer, primary key
> insdatetime timestamp w/o time zone
> ombcase_fkey integer, foreign key
> oldstatus_fkey integer, foreign key
> newstatus_fkey integer, foreign key
> active integer, not nullable
>
> The idea should be obvious, but to explain, insdatetime is set when a
> new record is created in any table. All records in ombcase have a
> foreign key to status that can't be null. When status changes, a record
> is created in statuschange recording the old and new status keys, and
> the time (etc).
>
> The goal is to find records in ombcase that have not had a status change
> in xx days. If the status has not changed, there will be no statuschange
> record.
>
> This query returns the age of each ombcase and the last statuschange
> record, but only if there is a statuschange record:
>
> --Finds the age and last status change for open cases, but not age of
> cases with no status change
>
> SELECT casename, age(ombcase.insdatetime) AS caseage,
> age(laststatuschange.created_at) AS statusage
>
> FROM
>
> (SELECT
>
> case_fkey, MAX(insdatetime) AS created_at
>
> FROM
>
> statuschange
>
> GROUP BY
>
> case_fkey) AS laststatuschange
>
> INNER JOIN
>
> ombcase
>
> ON
>
> laststatuschange.case_fkey = case_pkey
>
> RIGHT JOIN status
>
> ON status_fkey = status_pkey
>
> WHERE lower(statusid) NOT LIKE ('closed%')
>
> AND case_pkey <> 0
>
>
> I want to use coalesce
> (age(ombcase.insdatetime),age(statuschange.insdatetime) ) to return the
> time that a case has been in a status—or without a status change. But
> first I have to find the cases with no statuschange record. I was able
> to do that, too, using this query:
Outline form:
1) If a record is in ombcase it has a status('in a status') by definition.
From query below you are not looking for just records in ombcase, but
those that have a statusid other then 'closed%' in status table.
2) For the criteria in 1) you want to find the age of the last statuschange.
To me that leads to something like:
SELECT
case_pkey
FROM
ombcase AS
JOIN
status
ON
ombcase.case_pkey = status.status_fkey
LEFT JOIN
statuschange
ON -- Or statuschange.ombcase_fkey. Not clear from above.
statuschange.case_fkey = ombcase.status_pkey
GROUP BY
ombcase.pkey
HAVING
status.LOWER(statusid) NOT LIKE ('closed%')
AND
max(coalesce(statuschange.insdatetime, ombcase.insdatetime))
< 'some date'
Obviously not tested.
>
>
> --find cases in status too long
>
> SELECT casename, coalesce
> (age(ombcase.insdatetime),age(statuschange.insdatetime) )
>
> FROM ombcase
>
> LEFT JOIN statuschange
>
> ON case_fkey = case_pkey
>
> LEFT JOIN status
>
> ON status_fkey = status_pkey
>
> AND lower(statusid) NOT LIKE ('closed%')
>
> AND coalesce ( age(ombcase.insdatetime), age(statuschange.insdatetime) )
> > '2 months'
>
>
> But this query will return all statuschange records for an ombcase
> record that has multiple ones.
>
>
> Any suggestions on how to combine the two ideas?
>
>
> Chuck Martin
> Avondale Software
> --
> Chuck Martin
> Avondale Software
--
Adrian Klaver
adrian.klaver@aklaver.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 21:50 Chuck Martin <clmartin@theombudsman.com>
parent: Adrian Klaver <adrian.klaver@aklaver.com>
0 siblings, 1 reply; 70+ messages in thread
From: Chuck Martin @ 2019-01-27 21:50 UTC (permalink / raw)
To: Adrian Klaver <adrian.klaver@aklaver.com>; +Cc: pgsql-general
Chuck Martin
Avondale Software
On Sun, Jan 27, 2019 at 2:55 PM Adrian Klaver <adrian.klaver@aklaver.com>
wrote:
> On 1/26/19 3:04 PM, Chuck Martin wrote:
> [snip]
> Outline form:
>
> 1) If a record is in ombcase it has a status('in a status') by definition.
>
> From query below you are not looking for just records in ombcase, but
> those that have a statusid other then 'closed%' in status table.
>
> 2) For the criteria in 1) you want to find the age of the last
> statuschange.
>
> To me that leads to something like:
>
> SELECT
> case_pkey
> FROM
> ombcase AS
> JOIN
> status
> ON
> ombcase.case_pkey = status.status_fkey
> LEFT JOIN
> statuschange
> ON -- Or statuschange.ombcase_fkey. Not clear from above.
> statuschange.case_fkey = ombcase.status_pkey
> GROUP BY
> ombcase.pkey
> HAVING
> status.LOWER(statusid) NOT LIKE ('closed%')
> AND
> max(coalesce(statuschange.insdatetime, ombcase.insdatetime))
> < 'some date'
>
> Obviously not tested.
>
Thanks, Adrian. This got me a lot closer, but I'm puzzled by the number of
records returned. There are 3120 ombcase records with a statusid that is <>
'closed%':
SELECT count(ombcase.case_pkey)
FROM ombcase,status
WHERE ombcase.status_fkey = status.status_pkey AND lower(status.statusid)
NOT LIKE ('closed%')
But 3378 are returned by:
SELECT ombcase.case_pkey, ombcase.casename,
COALESCE(AGE(statuschange.insdatetime), AGE(ombcase.insdatetime)) AS
age_in_status
FROM ombcase
INNER JOIN status
ON ombcase.status_fkey = status.status_pkey
LEFT JOIN statuschange
ON statuschange.case_fkey = ombcase.case_pkey
GROUP BY ombcase.case_pkey, status.statusid, statuschange.insdatetime,
ombcase.insdatetime
HAVING LOWER(status.statusid) NOT LIKE ('closed%')
AND ombcase.case_pkey <> 0
AND MAX(COALESCE(AGE(statuschange.insdatetime), AGE(ombcase.insdatetime)))
> '2 months'
ORDER BY age_in_status DESC
I don't know where the extra 258 records came from, and I think I need to
keep working on it until the query returns 3120 records.
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 22:12 Adrian Klaver <adrian.klaver@aklaver.com>
parent: Chuck Martin <clmartin@theombudsman.com>
0 siblings, 0 replies; 70+ messages in thread
From: Adrian Klaver @ 2019-01-27 22:12 UTC (permalink / raw)
To: Chuck Martin <clmartin@theombudsman.com>; +Cc: pgsql-general
On 1/27/19 1:50 PM, Chuck Martin wrote:
>
> Chuck Martin
> Avondale Software
>
>
> On Sun, Jan 27, 2019 at 2:55 PM Adrian Klaver <adrian.klaver@aklaver.com
> <mailto:adrian.klaver@aklaver.com>> wrote:
>
> On 1/26/19 3:04 PM, Chuck Martin wrote:
> [snip]
> Outline form:
>
> 1) If a record is in ombcase it has a status('in a status') by
> definition.
>
> From query below you are not looking for just records in ombcase, but
> those that have a statusid other then 'closed%' in status table.
>
> 2) For the criteria in 1) you want to find the age of the last
> statuschange.
>
> To me that leads to something like:
>
> SELECT
> case_pkey
> FROM
> ombcase AS
> JOIN
> status
> ON
> ombcase.case_pkey = status.status_fkey
> LEFT JOIN
> statuschange
> ON -- Or statuschange.ombcase_fkey. Not clear from above.
> statuschange.case_fkey = ombcase.status_pkey
> GROUP BY
> ombcase.pkey
> HAVING
> status.LOWER(statusid) NOT LIKE ('closed%')
> AND
> max(coalesce(statuschange.insdatetime, ombcase.insdatetime))
> < 'some date'
>
> Obviously not tested.
>
>
> Thanks, Adrian. This got me a lot closer, but I'm puzzled by the number
> of records returned. There are 3120 ombcase records with a statusid that
> is <> 'closed%'
>
> SELECT count(ombcase.case_pkey)
>
> FROM ombcase,status
>
> WHERE ombcase.status_fkey = status.status_pkey AND
> lower(status.statusid) NOT LIKE ('closed%')
To get an apples to apples comparison what does below return?:
SELECT count(ombcase.case_pkey)
FROM ombcase
INNER JOIN status
ON ombcase.status_fkey = status.status_pkey
LEFT JOIN statuschange
ON statuschange.case_fkey = ombcase.case_pkey
AND
LOWER(status.statusid) NOT LIKE ('closed%')
Best guess is the 258 records are the ombcase records that have no
statuschange records, brought in by the LEFT JOIN.
>
>
> But 3378 are returned by:
>
> SELECT ombcase.case_pkey, ombcase.casename,
> COALESCE(AGE(statuschange.insdatetime), AGE(ombcase.insdatetime)) AS
> age_in_status
>
> FROM ombcase
>
> INNER JOIN status
>
> ON ombcase.status_fkey = status.status_pkey
>
> LEFT JOIN statuschange
>
> ON statuschange.case_fkey = ombcase.case_pkey
>
> GROUP BY ombcase.case_pkey, status.statusid, statuschange.insdatetime,
> ombcase.insdatetime
>
> HAVING LOWER(status.statusid) NOT LIKE ('closed%')
>
> AND ombcase.case_pkey <> 0
>
> AND MAX(COALESCE(AGE(statuschange.insdatetime),
> AGE(ombcase.insdatetime))) > '2 months'
>
> ORDER BY age_in_status DESC
>
> I don't know where the extra 258 records came from, and I think I need
> to keep working on it until the query returns 3120 records.
--
Adrian Klaver
adrian.klaver@aklaver.com
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 22:27 Chuck Martin <clmartin@theombudsman.com>
parent: Peter J. Holzer <hjp-pgsql@hjp.at>
0 siblings, 1 reply; 70+ messages in thread
From: Chuck Martin @ 2019-01-27 22:27 UTC (permalink / raw)
To: Peter J. Holzer <hjp-pgsql@hjp.at>; +Cc: pgsql-general@lists.postgresql.org
On Sun, Jan 27, 2019 at 8:07 AM Peter J. Holzer <hjp-pgsql@hjp.at> wrote:
> On 2019-01-26 18:04:23 -0500, Chuck Martin wrote:
> [snip]
> > The idea should be obvious, but to explain, insdatetime is set when a new
> > record is created in any table. All records in ombcase have a foreign
> key to
> > status that can't be null. When status changes, a record is created in
> > statuschange recording the old and new status keys, and the time (etc).
> >
> > The goal is to find records in ombcase that have not had a status change
> in xx
> > days. If the status has not changed, there will be no statuschange
> record.
>
> The easiest way is to use set operations:
>
> select case_pkey from ombcase;
> gives you all the ombcase ids.
>
> select ombcase_fkey from statuschange where insdatetime >= now()::date -
> xx;
> gives you all ombcase ids which had a status change in the last xx days.
>
> Therefore,
> select case_pkey from ombcase
> except
> select ombcase_fkey from statuschange where insdatetime >= now()::date -
> xx;
> gives you all ombcase ids which did /not/ have a status change in the
> last xx days.
>
I was not familiar with set operations, but studied up a bit and thought I
was getting there. Not quite, though. I have two queries that individually
return 1) all ombcase records with no statuschange record, and 2) the
newest statuschange record for each case that has a statuschange record.
But just putting UNION between then doesn't work. Here are my queries:
--First, find all open cases with no statuschange record
SELECT
case_pkey,statuschange_pkey,case_fkey,ombcase.insdatetime,statuschange.insdatetime
FROM
ombcase
LEFT JOIN
statuschange
ON
statuschange.case_fkey = case_pkey
AND case_pkey <> 0
LEFT JOIN
status
ON status_fkey = status_pkey
WHERE lower(statusid) NOT LIKE ('closed%')
AND statuschange.statuschange_pkey IS NULL
UNION
--Now find the last status change record for each case that has one
SELECT DISTINCT ON (case_fkey)
case_pkey,statuschange_pkey,case_fkey,ombcase.insdatetime,statuschange.insdatetime
FROM
statuschange,ombcase,status
WHERE case_fkey = case_pkey
AND status_fkey = status_pkey
AND LOWER(statusid) NOT LIKE ('closed%')
ORDER BY case_fkey, statuschange.insdatetime DESC
If I run each part separately, I get the expected number of records.
When I combine them with UNION, I get "missing FROM-clause entry for
table "statuschange"
So I'm very close here, and these two return the exact number of
records I'm expecting. So I just need to get them added together. Then
I expect I can put the whole thing in a WHERE clause with "AND
ombcase.case_pkey IN ([the combined results])"
>
> Another way would be to use a CTE
> (https://www.postgresql.org/docs/10/queries-with.html) to extract the
> last status change for each ombcase and then do a left join of ombcase
> to that CTE.
>
> hp
>
>
> --
> _ | Peter J. Holzer | we build much bigger, better disasters now
> |_|_) | | because we have much more sophisticated
> | | | hjp@hjp.at | management tools.
> __/ | http://www.hjp.at/ | -- Ross Anderson <https://www.edge.org/;
>
^ permalink raw reply [nested|flat] 70+ messages in thread
* Re: Query help
@ 2019-01-27 23:50 Chuck Martin <clmartin@theombudsman.com>
parent: Chuck Martin <clmartin@theombudsman.com>
0 siblings, 0 replies; 70+ messages in thread
From: Chuck Martin @ 2019-01-27 23:50 UTC (permalink / raw)
To: Peter J. Holzer <hjp-pgsql@hjp.at>; +Cc: pgsql-general@lists.postgresql.org
On Sun, Jan 27, 2019 at 5:27 PM Chuck Martin <clmartin@theombudsman.com>
wrote:
> On Sun, Jan 27, 2019 at 8:07 AM Peter J. Holzer <hjp-pgsql@hjp.at> wrote:
>
>> On 2019-01-26 18:04:23 -0500, Chuck Martin wrote:
>> [snip]
>> > The idea should be obvious, but to explain, insdatetime is set when a
>> new
>> > record is created in any table. All records in ombcase have a foreign
>> key to
>> > status that can't be null. When status changes, a record is created in
>> > statuschange recording the old and new status keys, and the time (etc).
>> >
>> > The goal is to find records in ombcase that have not had a status
>> change in xx
>> > days. If the status has not changed, there will be no statuschange
>> record.
>>
>> The easiest way is to use set operations:
>>
>> select case_pkey from ombcase;
>> gives you all the ombcase ids.
>>
>> select ombcase_fkey from statuschange where insdatetime >= now()::date -
>> xx;
>> gives you all ombcase ids which had a status change in the last xx days.
>>
>> Therefore,
>> select case_pkey from ombcase
>> except
>> select ombcase_fkey from statuschange where insdatetime >= now()::date -
>> xx;
>> gives you all ombcase ids which did /not/ have a status change in the
>> last xx days.
>>
>
> I was not familiar with set operations, but studied up a bit and thought I
> was getting there. Not quite, though. I have two queries that individually
> return 1) all ombcase records with no statuschange record, and 2) the
> newest statuschange record for each case that has a statuschange record.
> But just putting UNION between then doesn't work. Here are my queries:
>
> --First, find all open cases with no statuschange record
> SELECT
>
> case_pkey,statuschange_pkey,case_fkey,ombcase.insdatetime,statuschange.insdatetime
> FROM
> ombcase
> LEFT JOIN
> statuschange
> ON
> statuschange.case_fkey = case_pkey
> AND case_pkey <> 0
> LEFT JOIN
> status
> ON status_fkey = status_pkey
> WHERE lower(statusid) NOT LIKE ('closed%')
> AND statuschange.statuschange_pkey IS NULL
> UNION
> --Now find the last status change record for each case that has one
> SELECT DISTINCT ON (case_fkey)
>
> case_pkey,statuschange_pkey,case_fkey,ombcase.insdatetime,statuschange.insdatetime
> FROM
> statuschange,ombcase,status
> WHERE case_fkey = case_pkey
> AND status_fkey = status_pkey
> AND LOWER(statusid) NOT LIKE ('closed%')
> ORDER BY case_fkey, statuschange.insdatetime DESC
>
> If I run each part separately, I get the expected number of records. When I combine them with UNION, I get "missing FROM-clause entry for table "statuschange"
> So I'm very close here, and these two return the exact number of records I'm expecting. So I just need to get them added together. Then I expect I can put the whole thing in a WHERE clause with "AND ombcase.case_pkey IN ([the combined results])"
>
> This was pretty easy to resolve. Putting parentheses around each half of
the query caused it to return the right results. Then I could reduce the
columns to just ombcase.case_pkey and use an IN statement. I think this
gets me where I need to be. I appreciate the help!
Chuck
^ permalink raw reply [nested|flat] 70+ messages in thread
end of thread, other threads:[~2019-01-27 23:50 UTC | newest]
Thread overview: 70+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2001-08-11 11:04 Query help... Joshua Adam Ginsberg <rainman@owlnet.rice.edu>
2001-08-11 16:50 ` Thomas Lockhart <lockhart@fourpalms.org>
2001-08-11 17:06 ` Andrew Gould <andrewgould@yahoo.com>
2001-08-11 21:35 ` Lee Harr <missive@frontiernet.net>
2001-08-11 16:59 ` Andrew Gould <andrewgould@yahoo.com>
2001-08-30 23:45 query help G.L. Grobe <gary@grobe.net>
2001-08-31 00:22 ` Re: query help Stephan Szabo <sszabo@megazone23.bigpanda.com>
2001-08-31 12:41 Re: query help wsheldah@lexmark.com
2001-09-07 15:09 query help Jeff Patterson <jpat@mpip.org>
2001-09-14 19:49 ` Re: query help Oliver Elphick <olly@lfix.co.uk>
2001-09-07 15:43 query help Jeff Patterson <jpat@sonic.net>
2001-09-07 16:33 ` Re: query help Stephan Szabo <sszabo@megazone23.bigpanda.com>
2001-09-09 13:07 ` Re: query help Ian Barwick <SUNGLASSESbarwick@gmx.net>
2001-12-17 16:21 Query Help Joe Koenig <joe@jwebmedia.com>
2001-12-17 16:29 ` Re: Query Help Chris Albertson <chrisalbertson90278@yahoo.com>
2001-12-17 20:33 ` Re: Query Help Joe Koenig <joe@jwebmedia.com>
2001-12-17 21:10 ` Re: Query Help Darren Ferguson <darren@crystalballinc.com>
2001-12-18 09:35 ` Re: Query Help Antonio Fiol Bonnín <fiol@w3ping.com>
2001-12-17 16:42 ` Re: Query Help Andrew Gould <andrewgould@yahoo.com>
2002-07-23 23:39 Query Help Hunter Hillegas <lists@lastonepicked.com>
2002-07-24 00:28 ` Re: Query Help Stephan Szabo <sszabo@megazone23.bigpanda.com>
2002-12-03 23:16 [OFFTOPIC] Query Help Hunter Hillegas <lists@lastonepicked.com>
2002-12-03 23:29 ` Re: [OFFTOPIC] Query Help Jean-Luc Lachance <jllachan@nsd.ca>
2003-03-29 07:42 Query Help shreedhar <shreedhar@lucidindia.net>
2003-03-29 15:53 ` Re: Query Help Stephan Szabo <sszabo@megazone23.bigpanda.com>
2003-05-14 10:55 query help Rob Larter <rob@cdli.co.uk>
2003-05-14 15:41 ` Re: query help Stephan Szabo <sszabo@megazone23.bigpanda.com>
2007-01-19 17:05 Query Help Howard Cole <howardnews@selestial.com>
2007-01-19 18:52 ` Re: Query Help Tom Lane <tgl@sss.pgh.pa.us>
2007-01-21 20:08 ` Re: Query Help Howard Cole <howardnews@selestial.com>
2007-03-08 06:20 Query help Madison Kelly <linux@alteeve.com>
2007-03-08 06:46 ` Re: Query help Shaun Johnston <shaunj@benon.com>
2007-03-08 09:51 ` Re: Query help Richard Huxton <dev@archonet.com>
2007-03-09 02:46 ` Re: Query help Madison Kelly <linux@alteeve.com>
2007-08-14 20:10 query help Kirk Wythers <kwythers@umn.edu>
2007-08-15 03:20 ` Re: query help Josh Tolley <eggyknap@gmail.com>
2007-09-13 15:06 query help volunteer@spatiallink.org
2007-09-13 15:17 ` Re: query help Alexander Staubo <alex@purefiction.net>
2007-09-13 15:18 ` Re: query help Rodrigo De León <rdeleonp@gmail.com>
2007-09-13 15:32 Re: query help volunteer@spatiallink.org
2007-09-13 15:38 ` Re: query help Alexander Staubo <alex@purefiction.net>
2007-09-13 15:44 ` Re: query help Steve Crawford <scrawford@pinpointresearch.com>
2007-09-13 15:50 ` Re: query help brian <brian@zijn-digital.com>
2007-09-13 15:46 Re: query help volunteer@spatiallink.org
2007-09-13 16:31 Re: query help volunteer@spatiallink.org
2008-08-15 00:32 Query help novice <user.postgresql@gmail.com>
2008-08-15 01:51 ` Re: Query help Hui Xie <hui.xie@axisoft.com.hk>
2008-08-15 03:46 ` Re: Query help novice <user.postgresql@gmail.com>
2008-08-15 04:12 Re: Query help Brent Wood <b.wood@niwa.co.nz>
2016-10-05 03:31 Query help Bret Stern <bret_stern@machinemanagement.com>
2016-10-05 03:35 ` Re: Query help Rob Sargent <robjsargent@gmail.com>
2016-10-05 03:55 ` Re: Query help Daniel Caldeweyher <dcalde@gmail.com>
2019-01-01 19:05 Query help Chuck Martin <clmartin@theombudsman.com>
2019-01-01 19:14 ` RE: Query help Scot Kreienkamp <Scot.Kreienkamp@la-z-boy.com>
2019-01-01 19:26 ` Re: Query help John W Higgins <wishdev@gmail.com>
2019-01-01 19:44 ` Re: Query help Adrian Klaver <adrian.klaver@aklaver.com>
2019-01-01 20:05 ` Re: Query help David G. Johnston <david.g.johnston@gmail.com>
2019-01-01 22:10 ` Re: Query help Adrian Klaver <adrian.klaver@aklaver.com>
2019-01-01 19:28 ` Query help David G. Johnston <david.g.johnston@gmail.com>
2019-01-01 19:29 ` Re: Query help David G. Johnston <david.g.johnston@gmail.com>
2019-01-01 19:40 ` Re: Query help Adrian Klaver <adrian.klaver@aklaver.com>
2019-01-26 23:04 Query help Chuck Martin <clmartin@theombudsman.com>
2019-01-26 23:30 ` Re: Query help Ron <ronljohnsonjr@gmail.com>
2019-01-27 02:38 ` Re: Query help Charles Martin <ssappeals@gmail.com>
2019-01-27 13:07 ` Re: Query help Peter J. Holzer <hjp-pgsql@hjp.at>
2019-01-27 22:27 ` Re: Query help Chuck Martin <clmartin@theombudsman.com>
2019-01-27 23:50 ` Re: Query help Chuck Martin <clmartin@theombudsman.com>
2019-01-27 19:55 ` Re: Query help Adrian Klaver <adrian.klaver@aklaver.com>
2019-01-27 21:50 ` Re: Query help Chuck Martin <clmartin@theombudsman.com>
2019-01-27 22:12 ` Re: Query help Adrian Klaver <adrian.klaver@aklaver.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox