SQL Server:如何检索特定类别的每一行

时间:2017-12-31 09:47:59

标签: sql-server sql-server-2008

我有以下查询列出以下记录。但我想从下面的列表中只选择每个商店的一条记录。

如何优化以下查询来实现这一目标?

Select 
    o.StoreId,  
    o.OfferId,      
    OfferText       
From 
    Offers o 
Inner Join 
    (Select o1.StoreId
     From subcategorymap scm
     Inner Join Offers o1 On scm.OfferId = o1.OfferId   
     Where subcategoryid = 51
     Group By o1.StoreId
     Having Count(o1.StoreId) > 1) s1 On o.StoreId = s1.StoreId 

我想从下面的列表中为商店提取每条记录。

StoreId OfferId OfferText
-------------------------
14      46      Great Deal
21      60      30% OFF
21      61      Rs.50 OFF
21      61      Rs.50 OFF
14      84      10% OFF
14      84      10% OFF
14      86      30% OFF
19      196     Rs.50 OFF
166     219     20% OFF
166     221     30% OFF
166     223     10% OFF

输出应该是:

StoreId OfferId OfferText
-------------------------
14      46      Great Deal
21      60      Rs.30 OFF
19      196     Rs.50 OFF
166     219     20% OFF
...     ...     ...
...     ...     ...
...     ...     ...

3 个答案:

答案 0 :(得分:1)

使用Row_Number()

;With cte
As
(
Select 
RN = row_number() over(partition by o.storeid order by o.storeid,o.offerid),
    o.StoreId,  
    o.OfferId,      
    OfferText       
From 
    Offers o 
Inner Join 
    (Select o1.StoreId
     From subcategorymap scm
     Inner Join Offers o1 On scm.OfferId = o1.OfferId   
     Where subcategoryid = 51
     Group By o1.StoreId
     Having Count(o1.StoreId) > 1) s1 On o.StoreId = s1.StoreId
)
Select
*
From cte
Where RN = 1

答案 1 :(得分:0)

使用不同

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以使用MIN,例如:

Select 
    o.StoreId,  
    o.OfferId ,      
    OfferText       
From 
    Offers o 
Inner Join 
    (Select  o1.StoreId, MIN(o1.OfferId) OfferID
     From subcategorymap scm
     Inner Join Offers o1 On scm.OfferId = o1.OfferId   
     Where subcategoryid = 51
     Group By o1.StoreId
     Having Count(o1.StoreId) > 1) s1 On o.StoreId = s1.StoreId and  o.OfferID = s1.OfferID