473,666 Members | 2,069 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to retrieve the row which has a maximum value in a result of GROUP BY ?

296 Contributor
Hello,

I am using a GROUP BY in a query as follows -->

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM log GROUP BY name ORDER BY name,arrive,id desc
I want the rows which have the maximum id in the result of each "group by".

Please tell me how to do that ?
Jan 31 '07 #1
8 12919
pankajit09
296 Contributor
I think this might work -->

Expand|Select|Wrap|Line Numbers
  1. SELECT max(id),arrive,name FROM log group by name order by name,arrive
Jan 31 '07 #2
ronverdonk
4,258 Recognized Expert Specialist
That will not work. I show you an example:
Table zz:
Expand|Select|Wrap|Line Numbers
  1. +----+------------+------+
  2. | id | arrival    | name |
  3. +----+------------+------+
  4. |  1 | 2006-12-31 | John |
  5. |  2 | 2007-01-01 | John |
  6. |  3 | 2007-01-12 | John |
  7. |  4 | 2006-12-21 | Pete |
  8. |  5 | 2007-01-10 | Pete |
  9. |  6 | 2006-01-12 | Pete |
  10. |  7 | 2006-06-16 | Mark |
  11. +----+------------+------+
Executing your statement
Expand|Select|Wrap|Line Numbers
  1. SELECT max(id),arrival,name FROM zz 
  2.     GROUP BY name ORDER BY name,arrival;
produces the following result:
Expand|Select|Wrap|Line Numbers
  1. +---------+------------+------+
  2. | max(id) | arrival    | name |
  3. +---------+------------+------+
  4. |       3 | 2006-12-31 | John |
  5. |       7 | 2006-06-16 | Mark |
  6. |       6 | 2006-12-21 | Pete |
  7. +---------+------------+------+
There is no connection between the max(id) and the row content. MAX() is only executed AFTER a row has been read.
So, for your single statement solution you must use a subquery in the WHERE clause that returns the maximum id value per name, as in:
Expand|Select|Wrap|Line Numbers
  1. SELECT id as highest,arrival,name FROM zz 
  2.     WHERE id IN (SELECT MAX(id) FROM zz GROUP BY name);
That statement produces the required result:
Expand|Select|Wrap|Line Numbers
  1. +---------+------------+------+
  2. | highest | arrival    | name |
  3. +---------+------------+------+
  4. |       3 | 2007-01-12 | John |
  5. |       6 | 2006-01-12 | Pete |
  6. |       7 | 2006-06-16 | Mark |
  7. +---------+------------+------+
Ronald :cool:
Jan 31 '07 #3
pankajit09
296 Contributor
I must say you are brilliant Ronald.

You are a good observer.

This saved me of a major bug in my project.

I have no words to thank you.

My best wishes to you .
Feb 1 '07 #4
pankajit09
296 Contributor
But why you used "highest" in the Query above ?
Feb 1 '07 #5
pankajit09
296 Contributor
ok I got that is just for renaming the column.
Feb 1 '07 #6
ronverdonk
4,258 Recognized Expert Specialist
Glad to be of service.

And yes, the column name 'highest' was just to illustrate that it was actually the highest id that was shown.

Ronald :cool:
Feb 1 '07 #7
pankajit09
296 Contributor
But Ronald my actual query is like this -->

Expand|Select|Wrap|Line Numbers
  1. SELECT id,arrivedt,name,startdt,expiredt FROM act_log WHERE id IN(SELECT MAX(id) FROM act_log GROUP BY name) AND keywords REGEXP '".$keywords[0]."' OR keywords REGEXP'".$keywords[1]."' OR keywords REGEXP'".$keywords[2]."' AND csol='$csolnum'
  2. ORDER BY name

Its not working.
Please tell me why ?
Feb 2 '07 #8
pankajit09
296 Contributor
ok I got .

we have to put the OR conditions in bracket.

for eg:-

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM Persons WHERE
  2. (FirstName='Tove' OR FirstName='Stephen')
  3. AND LastName='Svendson'
Feb 2 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
28581
by: Kums | last post by:
What is the maximum permissible size of a database? Is there any limitation. What is the maximum # of tablespace's allowed in a database? Thanks for your response.
8
4689
by: Fred L. Kleinschmidt | last post by:
I need to know the largets value representable in a variable. However, I do not know the variable's true type - only that it is some kind of int. It may be any of the following: #typedef Newtype short; #typedef Newtype unsigned short; #typedef Newtype int; #typedef Newtype unsigned int; #typedef Newtype long; ....etc.
1
3359
by: Net Virtual Mailing Lists | last post by:
Hello, Lets say I have data like this: value1|value2|value3|value4|....|value(N) ------|------|------|------|----|-------- 100 | 200 | 300 | 400 | | 10 | 20 | | 40 | | | 15 | | 16 | |
6
2181
by: lovecreatesbeauty | last post by:
/* It seems that when an int with width of four bytes is assigned to a one byte width char, the first three bytes from left to right are discarded and the rightest byte is assigned to that char. So, I can just assign an int to a char to retrieve the rightest byte of that int, and I also use this method plus right-shift operation to get the leftest byte of an int.
29
5086
by: garyusenet | last post by:
I'm trying to investigate the maximum size of different variable types. I'm using INT as my starting variable for exploration. I know that the maximum number that the int variable can take is: 65,535. But i'm trying to write a program to test this, assuming I didn't know this number in advance. I came up with the following but have two questions. Maybe someone can help? using System; using System.Collections.Generic; using System.Text;
6
10673
by: =?Utf-8?B?U2hhcm9u?= | last post by:
I'm using the VScrollBar and set it as follow: m_vScrollBar.Minimum = -19602; m_vScrollBar.Maximum = 0; m_vScrollBar.SmallChange = 1; m_vScrollBar.LargeChange = 1089; m_vScrollBar.Value = m_vScrollBar.Maximum; The scroll bar is set to start from the bottom.
2
4122
by: Adam Teale | last post by:
hey guys Is there a builtin/standard install method in python for retrieving or finding out an image's dimensions? A quick google found me this: http://www.pythonware.com/library/pil/handbook/introduction.htm but it looks like it is something I will need to install - I'd like to be able to pass my script around to people without them needing any
2
4652
by: mndprasad | last post by:
Hi friends, Am new to AJAX coding, In my program am going to have two texbox which going to implent AJAX from same table. One box is going to retrieve the value of other and vice versa. I have implemented successfully for one text box, but it's done for the other field, since am getting script errors. <script> var queryField; var lookupURL; var divName;
4
3952
by: SjaakBanaan | last post by:
Hey all, I have a question that ought to be simple but has given me headaches for a while. I have a table with contact email addresses, say. T ID ContID Priority Emailaddress ----------------------------------------------
0
8444
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8639
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7386
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4368
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.