简体   繁体   English

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

[英]Select MAX and MIN value of the last 7 records inserted

I need to select the MAX and the MIN value of the last 8 records inserted for a specific device. 我需要选择为特定设备插入的最后8条记录的MAX和MIN值。 I have a table named letture with this structure: 我有一个名为letture的表,其结构如下:

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

on this table I made a query to extract the last 8 records for id_dispositivo = 1 在此表上,我进行了查询以提取id_dispositivo = 1的最后8条记录

SELECT valore FROM `letture` WHERE id_dispositivo = 1 ORDER BY id_lettura DESC LIMIT 0,8

On the result of this query I need to catch the MAX and the MIN value 在此查询的结果上,我需要捕获MAX和MIN值

You need a subquery: 您需要一个子查询:

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

Just use a subselect: 只需使用子选择:

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

---for sql server 2008 ---对于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM