选择插入的最后7条记录的MAX和MIN值

时间:2016-03-23 14:05:58

标签: php mysql sql database

我需要选择为特定设备插入的最后8条记录的MAX和MIN值。 我有一个名为 letture 的表,结构如下:

id,id_dispositivo,id_utenza,id_impianto,id_lettura,data,valore

在这张桌子上我做了一个查询,以提取id_dispositivo = 1

的最后8条记录
SELECT valore FROM `letture` WHERE id_dispositivo = 1 ORDER BY id_lettura DESC LIMIT 0,8

在此查询的结果中,我需要捕获MAX和MIN值

3 个答案:

答案 0 :(得分:3)

你需要一个子查询:

SELECT MIN(valore), MAX(valore)
FROM (SELECT valore
      FROM `letture`
      WHERE id_dispositivo = 1
      ORDER BY id_lettura DESC
      LIMIT 8
     ) last8;

答案 1 :(得分:3)

只需使用子选择:

SELECT MIN(valore), MAX(valore) FROM (
  SELECT valore 
  FROM `letture` 
  WHERE id_dispositivo = 1 ORDER BY id_lettura DESC LIMIT 0,8
) T1;

答案 2 :(得分:0)

---对于sql server 2008

Create Table Testing(TestID Integer Primary Key,Price Float);
Insert Into Testing Values (1,12.00);
Insert Into Testing Values (2,15.00);
Insert Into Testing Values (3,20.00);
Insert Into Testing Values (4,13.00);
Insert Into Testing Values (5,11.00);
Insert Into Testing Values (6,12.00);
Insert Into Testing Values (7,17.00);
Insert Into Testing Values (8,18.00);
Insert Into Testing Values (9,19.00);
Insert Into Testing Values (10,22.00);

Create Function dbo.GetMinID(@MaxId Integer,@NoOfRows Integer) Returns Integer
as 
Begin
    Declare @MinMax Integer
    IF @NoOfRows > 1  
    Set @MinMax=dbo.GetMinID((Select MAX(TestID) From Testing where TestID <@MaxId),@NoOfRows-1)
    else 
    Set @MinMax=(Select MAX(TestID) From Testing where TestID < @MaxId);                
    Return @MinMax;
End 

Select R.TestID,dbo.GetMinID(R.TestID,8) as MinMax From (Select MAX(TestID) TestID
From Testing) R