如何在sqlite中选择最小值?

时间:2013-12-18 13:13:31

标签: sql sqlite

我有MS_FireStationOriginalMI表数据:

 FireStation FireStationOriginalCode SortNo  Micode
    1                 1                  1    1
    1                 2                  1    2
    1                 3                  2    3
    1                 4                  1    2

重点:FireStation FireStationOriginalCode 我将查询写为:

SELECT   Min(SortNo) as SortNo,m.FireStationOriginalCode
    FROM MS_FireStationOriginalMI m
    GROUP BY MICode

结果:

SortNo  FireStationOriginalCode
2          4
3          3
1          1

为什么呢? SortNo =2 but get FireStationOriginalCode=4

我想要SortNo =2 and FireStationOriginalCode=2

SortNo  FireStationOriginalCode
    2          2
    3          3
    1          1

如何写sql?

4 个答案:

答案 0 :(得分:1)

您的聚合函数MIN位于错误的列中(SQLite以外的SQL引擎会抱怨它)!

SELECT  SortNo, MIN(m.FireStationOriginalCode)
FROM MS_FireStationOriginalMI m
GROUP BY MICode;

将返回所需的结果。 SQL Fiddle

编辑:你的问题我不清楚,但知道我认为我明白了:

SELECT o.SortNo, o.FireStationOriginalCode
FROM MS_FireStationOriginalMI o
INNER JOIN (
  SELECT  MICode, MIN(SortNo) AS SortNo
  FROM MS_FireStationOriginalMI m
  GROUP BY MICode
) AS m ON m.MICode=o.MICode AND m.SortNo=o.SortNo;

将为每个(SortNo, FireStationOriginalCode)返回SortNo匹配的最小MICodeSQL Fiddle

答案 1 :(得分:1)

SELECT x.a
     , x.b
     , x.c
  FROM my_table x
  JOIN (SELECT b,MIN(c) min_c FROM my_table GROUP BY b) y
    ON y.b = x.b
   AND y.min_c = x.c

答案 2 :(得分:0)

SELECT   Min(SortNo) as SortNo,m.FireStationOriginalCode
    FROM MS_FireStationOriginalMI m
    GROUP BY m.FireStationOriginalCode

答案 3 :(得分:0)

我可以通过sql获得3行:

SELECT m.*
  FROM MS_FireStationOriginalMI m
  Where m.FireStationOriginalCode=(Select b.FireStationOriginalCode from      MS_FireStationOriginalMI b where m.firestation = b.firestation and m.micode = b.micode  order by b.sortno limit 1)