需要SQL查询的解决方案

时间:2014-06-02 11:42:24

标签: sql

我的SQL查询是,

SELECT 
    T.TAX_NAME,A.TAX_AMT_ID,A.TAX_MAP_ID,A.EFFECTIVE_FROM 
FROM 
    MAS_TAX T   
INNER JOIN  
    MAS_TAX_MAP M ON T.TAX_ID = M.TAX_ID 
LEFT OUTER JOIN 
    MAS_TAX_AMOUNT A ON M.TAX_MAP_ID = A.TAX_MAP_ID 
WHERE  
    EFFECTIVE_FROM <= GETDATE()             

我正在获得上述查询的输出:

TAX_NAME    TAX_AMT_ID  TAX_MAP_ID  EFFECTIVE_FROM
-------------------------------------------------------
Income Tax  12     5        02-06-2014
Service Tax 16     4        02-06-2014
Gift Tax    3      1        29-05-2014
Gift Tax    2      1        28-05-2014
Gift Tax    4      1        27-05-2014

但我需要低于输出。谁能帮我?

TAX_NAME    TAX_AMT_ID  TAX_MAP_ID  EFFECTIVE_FROM
-------------------------------------------------------
Income Tax  12     5        02-06-2014
Service Tax 16     4        02-06-2014
Gift Tax    3      1        29-05-2014

1 个答案:

答案 0 :(得分:2)

您似乎想要最新的记录。您可以使用row_number()

在SQL Server中执行此操作
select TAX_NAME, TAX_AMT_ID, TAX_MAP_ID, EFFECTIVE_FROM
from (select t.*,
             row_number() over (partition by tax_name order by effective_from desc) as seqnum
      from table t
     ) t
where seqnum = 1;

编辑:

针对您的特定查询:

SELECT T.TAX_NAME, A.TAX_AMT_ID, A.TAX_MAP_ID, A.EFFECTIVE_FROM
FROM (SELECT T.TAX_NAME, A.TAX_AMT_ID, A.TAX_MAP_ID, A.EFFECTIVE_FROM,
             ROW_NUMBER() OVER (PARTITION BY T.TAX_NAME ORDER BY A.EFFECTIVE_FROM DESC) as seqnum
      FROM MAS_TAX T INNER JOIN
           MAS_TAX_MAP M
           ON T.TAX_ID = M.TAX_ID LEFT OUTER JOIN
           MAS_TAX_AMOUNT A
           ON M.TAX_MAP_ID = A.TAX_MAP_ID 
      WHERE EFFECTIVE_FROM <= GETDATE() 
     ) t
WHERE seqnum = 1;