The fields you get returned are not necessarily the fields from the exact same row in a collection of group by rows.  This is relevant when you for instance want to get the first occurrence of something within the group by, i.e. the row with the earliest datetime value (which wasn't used to group by).  In this situation you can't rely on the GROUP BY to give you that. The ORDER BY you use will have no effect on the aggregation performed by the GROUP BY as it is only applied afterwards on the results of the GROUP BY.  The values returned have to be assumed to be from a random row / rows within the group.  There is a solution however – see below

How To Get Sort Within A Group By

Example of how to get the earliest datetime row value within a GROUP BY:

	Command1->CommandText = "SELECT LogMeltCode, datetime(MIN(LogDateTime)) as LogDateTime, LogLotNo, LogWorker, LogInstrumentNo \
								FROM tblLogEvents \
								GROUP BY LogMeltCode, LogLotNo, LogWorker, LogInstrumentNo \
								ORDER BY " + SearchOrderBy;
	//The MIN() above ensures we get the earliest occurance of that field




We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.


Your email address will not be published.