【问题标题】:Select second highest value per distinct foreign key为每个不同的外键选择第二大值
【发布时间】:2012-10-05 19:38:26
【问题描述】:

所以,我有两个表,帐户和发票,它们由帐户表中的主键链接,即。 account.key 和 invoice.key。

我想为每个帐户的第二个最新发票日期选择 account.accountnumber、invoice.invoicedate、invoice.invoiceamount。

有什么想法吗?

所以要选择所有发票及其对应的帐号:

select a.accountnumber, i.invoicedate, i.invoiceamount
from account a
join invoice i on (a.key = i.key)

并从整个发票表中选择第二张最新发票:

select MAX(invoicedate) from INVOICE i where invoicedate NOT IN (SELECT MAX(invoicedate) from i

但是我如何从 invoice 表中获取每个帐户的第二张最新发票,以及 account 表中的帐号?

提前致谢。

【问题讨论】:

    标签: sql sql-server sql-server-2005


    【解决方案1】:

    通过使用ROW_NUMBER() 窗口函数...

    select accountnumber, invoicedate, invoiceamount 
    from 
    (
        select a.accountnumber, i.invoicedate, i.invoiceamount, 
            row_number() over (partition by a.accountnumber order by invoicedate desc) rn
        from account a 
            join invoice i on a.[key] = i.[key]
    ) v
    where rn = 2
    

    【讨论】:

      【解决方案2】:

      尝试使用这个:

      select a.accountnumber, i.invoicedate, i.invoiceamount 
      from account a 
      join invoice i on a.[key] = i.[key]
      and i.invoicedate in
      (select max(invoicedate) as secondmaxdate from invoice where invoicedate not in
      (select max(invoicedate) as maxdate from invoice group by [key])
      group by [key])
      

      【讨论】:

      • 这不仅过于复杂,而且如果发票共享日期,它将无法工作。
      猜你喜欢
      • 2017-07-24
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2021-05-10
      • 2016-04-10
      相关资源
      最近更新 更多