SQL查询-合并两个表,删除重复项,仅保留最新的日期

问题描述 投票:0回答:2

[我正在尝试在SQLServer Management Studio 2008中将一个查询放在一起,我通过'tax_id'将两个表联接在一起,但是我从表2(Tax_Rate_Table)中有一个重复的条目,我只需要在其中显示一个条目即可。您可以在下面看到最新的“有效日期”,Tax_ID 4具有重复的条目:

1.TAX_TABLE---------    
tax_id  description

        1   AZ State
        2   AZ-Maricopa Co
        4   AZ-Maricopa/Mesa



2.Tax_RATE_TABLE-------
tax_id  effective_date  tax_percent

1   2015-01-01 00:00:00.000 5.6
2   2015-01-01 00:00:00.000 0.7
4   2015-01-01 00:00:00.000 1.75
4   2019-03-01 00:00:00.000 2

我按有效日期加入和降序有效,但是,我尝试使用“按有效日期降序限制1排序;”但是限制功能不起作用。

sql sql-server sql-server-2008 join greatest-n-per-group
2个回答
0
投票

一个选项使用横向联接(不是SQL Server不支持limit语法,而是使用top):

select t.*, tr.effective_date, tr.tax_percent
from tax_table t
cross apply (
    select top (1) *
    from tax_rate_table tr
    where tr.tax_id = t.tax_id
    order by tr.effective_date desc
) tr

您也可以加入和过滤相关子查询:

select t.*, tr.effective_date, tr.tax_percent
from tax_table t
inner join tax_rate_table tr on tr.tax_id = t.tax_id
where tr.effective_date = (
    select max(tr1.effective_date)
    from tax_rate_table tr1
    where tr1.tax_id = tr.tax_id
)

或者您可以使用row_number()

select *
from (
    select 
        t.*, 
        tr.effective_date, 
        tr.tax_percent,
        row_number() over(partition by t.tax_id order by tr.effective_date desc) rn
    from tax_table t
    inner join tax_rate_table tr on tr.tax_id = t.tax_id
) t
where rn = 1

0
投票
;with rates
AS
(
    SELECT *
    ,ROW_NUMBER() OVER (PARTITION BY tax_id ORDER BY effective_date desc) as pID
    FROM tax_table t
        inner join tax_rate_table r on t.ID = r.tax_id
)

select
    tax_id
    ,DESCRIPTION
    ,effective_date
    ,percentage
FROM rates
WHERE pid = 1
© www.soinside.com 2019 - 2024. All rights reserved.