用其他字段的最小值进行数据聚合

时间:2015-04-22 17:49:02

标签: mysql sql

我在MySQL数据库中有一个这样的表。

Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
    If txtWeight.Text <= 27 Then
        Me.lblAnswer.Text = "Accepted"
    ElseIf txtWeight.Text >= 27 Then
        Me.lblAnswer.Text = "Rejected: Too heavy"
    End If
    If txtLength.Text <= 100 Then
        Me.lblAnswer.Text = "Accepted"
    ElseIf txtLength.Text >= 100 Then
        Me.lblAnswer.Text = "Rejected: Too large"
    End If
    If lblWidth.Text <= 100 Then
        Me.lblAnswer.Text = "Accepted"
    ElseIf txtWidth.Text >= 100 Then
        Me.lblAnswer.Text = "Rejected: Too large"
    End If
    If txtHeight.Text <= 100 Then
        Me.lblAnswer.Text = "Accepted"
    ElseIf txtHeight.Text >= 100 Then
        Me.lblAnswer.Text = "Rejected: Too large"
    End If
End Sub

我正在基于Name Age code foo 24 23 bar 23 21 mit 19 23 属性进行数据聚合,因为我在mysql中使用"code"就像这样

"group by"

输出

Select * from table group by code

我只对最小年龄的汇总结果感兴趣。

预期输出

foo 24 23
bar 23 21

我正在寻找最优化的查询。

提前致谢。如果您需要更多详细信息,请与我们联系。

3 个答案:

答案 0 :(得分:0)

您希望每个代码具有最小年龄的行。这意味着代码没有更小的年龄。这是一种方法:

select t.*
from table t
where not exists (select 1 from t2 where t2.code = t.code and t2.age < t.age);

答案 1 :(得分:0)

您可以使用

获取每个代码的最小年龄
SELECT code, MIN(age) FROM table GROUP BY code

如果你想要name对应agecode SELECT code, age, name FROM table JOIN (SELECT code, MIN(age) age FROM table GROUP BY code) t USING (code, age) ,那么很遗憾它会变得更加棘手。这将有效:

d <- data.frame(
  state = rep(c('NY', 'CA'), 10),
  year = rep(1:10, 2),
  response= rnorm(20)
)

library(plyr)
models <- dlply(d, "state", function(df) 
  lm(response ~ year, data = df))

ldply(models, coef)
l_ply(models, summary, .print = TRUE)

如果您在表格中提供索引,则可以进行一些优化。

答案 2 :(得分:0)

http://sqlfiddle.com/#!9/8e0e9/3

SELECT t.* 
FROM table1 t
LEFT JOIN table1 t2
ON t.code = t2.code
  AND t.age>t2.age
WHERE t2.name IS NULL