选择查询以基于获取最大日期显示行

时间:2014-04-10 04:37:18

标签: sql sql-server-2008

我有以下查询

 Select  distinct    
     a.Item_Name, b.Item_Rate, b.professional_Charge,
     c.discount, c.discount_Type,
     a.Dept_ID, c.Discount_Applicability, 
     c.Effective_Date, b.Effective_Date
 From 
     Item_M a
 left outer join 
     Rate_M b on a.Item_Code = b.Bill_Item and b.Rate_Cat_ID = 'GEN'
 left outer join 
     Discount_M c on a.Item_Code = c.Item_Code and c. Pay_Type_Id='CS'
 Where 
     a.Item_code = 'ABS002' 
     and c.Effective_Date <= GETDATE()
     and b.Effective_Date <= GETDATE()
 group by  
     a.Item_Name, b.Item_Rate, b.professional_Charge,
     c.discount, c.discount_Type,
     a.Dept_ID, c.Discount_Applicability, c.Effective_Date, b.Effective_Date
 order by 
     c.Effective_Date, b.Effective_Date desc

输出如下所示:

 Item_Name  Item_Rate   professional_Charge discount    discount_Type   Dept_ID Discount_Applicability  Effective_Date  Effective_Date
 ----------------------------------------------------------------------------------------------------------------------------------------------------------
 ABSESS I & D 75          NULL                 0           P             CBN     I                   2014-04-06 12:34:36.530    2014-04-09 15:15:56.367
 ABSESS I & D 440         NULL                 0           P             CBN    I                    2014-04-06 12:34:36.530    2014-04-07 15:15:56.367
 ABSESS I & D 75          NULL                 0           P             CBN    I                    2014-04-09 16:36:05.790    2014-04-09 15:15:56.367
 ABSESS I & D 440         NULL                 0           P             CBN    I                    2014-04-09 16:36:05.790    2014-04-07 15:15:56.367

现在我需要的预期输出是得到一行,其中两个生效日期都是最大值,即在上面的输出中我需要在输出中显示 3rd 行。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

当您使用SQL Server 2008时,是时候学习窗口功能了。我将在你的情况下使用的那个是ROW_NUMBER()(虽然也可以使用RANK)。您还应该学习如何使用CTE(公用表表达式)。它们是现代SQL中真正的生命储蓄者。如果您将此知识应用于您的问题,查询将看起来像这个简单:

; with b AS(
SELECT Item_Rate, Bill_Item, 
professional_Charge, 
Effective_Date, 
ROW_NUMBER() OVER (PARTITION BY Bill_Item ORDER BY Effective_Date DESC) rn
FROM Rate_M WHERE Rate_Cat_ID = 'GEN' and Effective_Date <= GETDATE()),
c AS 
(SELECT discount, Item_Code,
discount_Type,
Discount_Applicability, 
Effective_Date,
ROW_NUMBER() OVER (PARTITION BY Item_Code ORDER BY Effective_Date DESC) rn
FROM Discount_M WHERE Pay_Type_Id='CS' and Effective_Date <= GETDATE())
 Select  
     a.Item_Name, b.Item_Rate, b.professional_Charge,
     c.discount, c.discount_Type,
     a.Dept_ID, c.Discount_Applicability, 
     c.Effective_Date, b.Effective_Date
 From 
     Item_M a
 left outer join 
     b on a.Item_Code = b.Bill_Item and b.rn = 1
 left outer join 
     c on a.Item_Code = c.Item_Code and c.rn = 1
 Where 
     a.Item_code = 'ABS002' 
 order by 
     c.Effective_Date, b.Effective_Date desc
相关问题