SQL查询在子查询中查找MAx行

时间:2009-08-22 07:46:41

标签: sql max row sql-server-2000

这些是我的表格:

User, Product, DiscountGroup, DiscountUser, DiscountProduct.

DiscountProduct:

id    discountGroupId    productId     discount
---   --------------     ---------     -------
1        2                8             2000
2        3                8             1000
3        2                4              4500

DiscountUser:

id    discountGroupId    userId   
---   --------------     --------- 
1        2                2        
2        3                3        
3        2                2    

DiscountGroup:

id    title   active
---   ------ --------     
1       A      1         
2       B      0       
3       C       1    

我使用SQL Server 2000。

我想要的是什么:

首先:对于每个productid和成员找到它们都属于它的discountGroup。

我写了我的查询:

select * 
from discountGroup 
where id in (select discountgroupId 
             from discountproduct 
             where productid = 11)
  and id in (select discountgroupId 
             from discountuser 
             where userid = 2)
  and active = 1

第二:我想找到特殊产品和会员的最大折扣。

我该怎么做?

第三:对于特殊用户和所有产品,我想找到最佳折扣和折扣组标题:

同样如此:

user  produc    discount   discountGroup
---   -----     -------    ------------
ali   phone     400            A
reeza mobile     200           B 

1 个答案:

答案 0 :(得分:1)

不要使用子查询,请使用连接:

select g.id, p.discount
from DiscountGroup g
inner join DiscountProduct p on p.discountGroupId = g.id
inner join DiscountUser u on u.discountGroupId = g.id
where p.productid = 11 and u.userid = 2

要获得最大折扣,请使用max aggregate:

select max(p.discount)
from DiscountGroup g
inner join DiscountProduct p on p.discountGroupId = g.id
inner join DiscountUser u on u.discountGroupId = g.id
where p.productid = 11 and u.userid = 2