如何查询Select,Group,然后使用date约束进行Join

时间:2015-02-12 01:50:36

标签: sql sql-server

我在创建查询以满足要求时遇到了一些问题。这种形式有两个表:

Names(nameID(PK), name,...);
Invoices(nameID(FK), invoiceID, invoiceDate, invoiceTotal,...);

我想显示所有这些列(Name,invoiceID,invoiceDate,invoiceTotal),但必须显示最近的发票日期。因此,多个名称可以与发票的不同实例相关联,我只想显示最新的。

我能够得到这个:

select 
Names.name, max(Invoices.invoiceDate) as "Newest Invoice"
from 
Names, Invoices
where 
Names.nameID = Invoices.nameID
group by 
Names.name;

显然,这只会显示正确的名称及其最新发票。

-----------------------------
| Name        |Newest Invoice|
--------------|---------------
|Name1        | 2011-08-22   |
--------------|---------------
|Name2        | 2012-07-23   |
------------------------------

我试图让它包含列'invoiceID和invoiceTotal',但它需要一个分组,然后会搞乱初始意图。我试图嵌套选择,它真的很乱,不会运行。有关如何构建嵌套选择的任何见解(如果这是优化的解决方案)。

1 个答案:

答案 0 :(得分:1)

使用Window Function获取每invoiceDate

最多Name
select Names,InvoiceDate,invoiceID,invoiceTotal
from 
(
select 
Names.name,Row_number()over(partition by Names.name order by Invoices.invoiceDate Desc) As Rn,Invoices.Names,Invoices.invoiceDate,
Invoices.invoiceID, Invoices.invoiceTotal
from 
Names Join Invoices
On
Names.nameID = Invoices.nameID
) A
where Rn=1