If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > PostgreSQL > Try to figure this one out? Getting one column value based on order of another.

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-18-11, 13:17
ss1289 ss1289 is offline
Registered User
 
Join Date: Jan 2009
Posts: 12
Try to figure this one out? Getting one column value based on order of another.

Hi,
I'm trying to build a query that will pull a single primary key id based on the minimum value of another column which is grouped by a foreign key.

For Ezxample:
Code:
Column 1 | Column 2 | Column 3
(PK)         (FK)         (Year)
-------------------------------
1111         101           2008
1222         101           2007
1333         101           2010
I want to get the PK id of 1222 because it's the smallest Year of FK 101.

My initial query was to select the smallest PK, but that was assuming that the PKs were created in order by year. However 2007 could be created after 2008.
Reply With Quote
  #2 (permalink)  
Old 04-18-11, 17:02
shammat shammat is offline
Registered User
 
Join Date: Nov 2003
Posts: 2,408
Code:
SELECT *
FROM the_table_with_no_name
WHERE column_3 = (SELECT min(t2.column_3)
                  FROM the_table_with_no_name t2
                  WHERE t2.column_2 = 101)
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On