簡體   English   中英

選擇最后插入的7條記錄的MAX和MIN值

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

我需要選擇為特定設備插入的最后8條記錄的MAX和MIN值。 我有一個名為letture的表,其結構如下:

id,id_dispositivo,id_utenza,id_impianto,id_lettura,數據,valore

在此表上,我進行了查詢以提取id_dispositivo = 1的最后8條記錄

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

在此查詢的結果上,我需要捕獲MAX和MIN值

您需要一個子查詢:

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

只需使用子選擇:

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

---對於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