SQL Query(和NSPredicate)帮助:Group By的最小值

时间:2013-02-21 20:08:36

标签: sql sqlite core-data nspredicate

这可能是一个非常初学者的sql语句,但由于某些原因我遇到了为这个简单的表编写查询的困难:

id  name    value
1   Felix   1
2   Bob     2
3   Charles 3
4   Mike    4
5   John    4
6   Peter   2
7   Felix   2
8   Felix   3

这是一张简单的表格。我想按名称分组,每组都有最小值。例如,查询应该返回:

1 Felix 1
2 Bob 2
3 Charles 3
4 Mike 4
5 John 4 
6 Peter 2

我试过了:

SELECT * FROM TABLE GROUP BY name HAVING min(value);

但它没有用。

如果您可以在CoreData中为我提供NSPredicate,那么也可以获得奖励积分。

谢谢!

3 个答案:

答案 0 :(得分:1)

Select min(ID), Name, min(value)
From yourtable
Group by  name

答案 1 :(得分:1)

您还可以使用子查询和JOIN。子查询为每个min(value)获取name,然后将其加入到您的表中:

select t1.id,
  t1.name,
  t1.value
from yourtable t1
inner join
(
  select name, min(value) MinVal
  from yourtable
  group by name
) t2
  on t1.name = t2.name
  and t1.value = t2.minval
order by t1.id

请参阅SQL Fiddle with Demo

答案 2 :(得分:1)

这是一个NSFetchRequest版本

NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Table"];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"value"];
NSExpression* expr = [NSExpression expressionForFunction:@"min:" arguments:@[keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"value"];
[expressionDescription setExpression:expr];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
[request setPropertiesToGroupBy:@[@"name"]];
[request setPropertiesToFetch:@[@"name",expressionDescription]];
NSError* error = nil;
NSArray* rez = [managedObjectContext executeFetchRequest:request error:&error];