MIN和MAX分别具有IDS

时间:2013-12-01 22:59:15

标签: sql sql-server

如何在一次查询中完成这些查询

select top 1 @nMinor = SHI_nPayable , @minrecno = SHI_iItemPK 
    from StmHistItm sqi1
    where sqi1.SHI_cfamily=@cfamily and 
          sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable < 0
    order by sqi1.shi_crecip_id,sqi1.SHI_cfamily, sqi1.SHI_dPubdate,sqi1.SHI_cIsbn

Select top 1  @nMayor =  SHI_nPayable , @maxrecno = SHI_iItemPK ,
     @nPayable1 = @nMayor  + @nMinor 
     from StmHistItm sqi1
     where sqi1.SHI_cfamily=@cfamily and 
           sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable > 0
     order by sqi1.shi_crecip_id,sqi1.SHI_cfamily,sqi1.SHI_dPubdate ,sqi1.SHI_cIsbn

我尝试进行此查询,但我没有获取最大值和最小值的ID。

select  min(SHI_nPayable),  MAX(SHI_nPayable),
   from StmHistItm sqi1
   where sqi1.SHI_cfamily=@cfamily and 
         sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable <> 0
    group by SHI_cRecip_ID,SHI_cFamily  

1 个答案:

答案 0 :(得分:0)

试试这个..

SELECT A.SHI_nPayable, A.SHI_iItemPK , B.SHI_nPayable, B.SHI_iItemPK 
FROM (select top 1 SHI_nPayable ,  SHI_iItemPK 
    from StmHistItm sqi1
    where sqi1.SHI_cfamily=@cfamily and 
          sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable < 0
    order by sqi1.shi_crecip_id,sqi1.SHI_cfamily, sqi1.SHI_dPubdate,sqi1.SHI_cIsbn)A,
    (Select top 1   SHI_nPayable ,  SHI_iItemPK  
     from StmHistItm sqi1
     where sqi1.SHI_cfamily=@cfamily and 
           sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable > 0
     order by sqi1.shi_crecip_id,sqi1.SHI_cfamily,sqi1.SHI_dPubdate ,sqi1.SHI_cIsbn)B

如果你想将返回的结果存储在变量中,你可以在外部SELECT这样做

SELECT @Var1 = A.SHI_nPayable, @Var2 = A.SHI_iItemPK 
      ,@Var3 =  B.SHI_nPayable, @Var4 = B.SHI_iItemPK 
FROM (select top 1 SHI_nPayable ,  SHI_iItemPK 
    from StmHistItm sqi1
    where sqi1.SHI_cfamily=@cfamily and 
          sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable < 0
    order by sqi1.shi_crecip_id,sqi1.SHI_cfamily, sqi1.SHI_dPubdate,sqi1.SHI_cIsbn)A,
    (Select top 1   SHI_nPayable ,  SHI_iItemPK  
     from StmHistItm sqi1
     where sqi1.SHI_cfamily=@cfamily and 
           sqi1.shi_crecip_id=@crecipid  and sqi1.SHI_nPayable > 0
     order by sqi1.shi_crecip_id,sqi1.SHI_cfamily,sqi1.SHI_dPubdate ,sqi1.SHI_cIsbn)B