【问题标题】:SQL Query - Combining Two tables, removing duplicates and only keeping most recent by dateSQL 查询 - 组合两个表,删除重复项并仅保留最新的日期
【发布时间】:2020-08-04 11:43:26
【问题描述】:

我正在尝试在 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

我的加入和按生效日期降序有效,但是,我正在尝试使用“order by effective_date desc LIMIT 1;”但是限制功能不起作用。

【问题讨论】:

    标签: sql sql-server sql-server-2008 join greatest-n-per-group


    【解决方案1】:

    一个选项使用横向连接(并不是说 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
    

    【讨论】:

    • 谢谢,这里有严格的截止日期,SQL 不是我在这个项目中的专长!我利用相关子查询的方法来解决。
    【解决方案2】:
    ;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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2021-11-16
      • 2013-07-10
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多