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 > MySQL > Query Problem

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-06-10, 10:40
datune datune is offline
Registered User
 
Join Date: Jan 2004
Posts: 6
Question Query Problem

Hello,

I am struggling trying to achieve the following:

Table has 4 columns:
id
session_id
x
y

5 Sample records
1, 1, 10, 20
2, 1, 5, 10
3, 1, 2, 4
4, 2, 5, 10
5, 2, 2, 4

SELECT t1.id, t1.session_id, t1.diff FROM (SELECT id, session_id, y-x as diffFROM poker_sessions) as t1 WHERE MAX(t1.diff)

What I want is to have the maximum difference PER session_id

So I expect two records:

1, 1, 10 (ten is the highest difference)
4, 2, 5 (five being the highest difference for session_id 2)

I can't seem to figure out how to do that. I would really appreciate some help, I have tried everything I can think off, to no avail. Thanks!
Reply With Quote
  #2 (permalink)  
Old 02-06-10, 10:57
r937 r937 is online now
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
Code:
SELECT t.id
     , t.session_id
     , t.y - t.x AS diff
  FROM ( SELECT session_id 
              , MAX(y-x) AS max_diff
           FROM poker_sessions
         GROUP
             BY session_id ) AS m
INNER
  JOIN poker_sessions AS t
    ON t.session_id = m.session_id
   AND t.y - t.x = m.max_diff
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 02-06-10, 11:06
datune datune is offline
Registered User
 
Join Date: Jan 2004
Posts: 6
Nice r937!

Thanks a lot!
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