查询每个相关客户的最大发票,而不是该客户的每张发票

时间:2013-11-12 18:00:41

标签: sql sql-server-2012 greatest-n-per-group

我需要编写一个查询来显示阿拉巴马州每位客户(包括阿拉巴马州从未有过的任何客户)所做的最大购买的客户代码,客户名,姓氏,完整地址,发票日期和发票总额进行了购买;他们的发票日期应为NULL,发票总额应显示为0)。

Here is an ERD of the two required tables.

Here is what my latest query looks like.

select distinct lgcustomer.cust_code
      ,Cust_FName
      ,Cust_LName
      ,Cust_Street
      ,Cust_City
      ,Cust_State
      ,Cust_ZIP
      ,max(inv_total) as [Largest Invoice]
      ,inv_date
from lgcustomer left join lginvoice on lgcustomer.cust_code = lginvoice.cust_code
where Cust_State = 'AL'
group by lgcustomer.cust_code
      ,Cust_FName
      ,Cust_Lname
      ,Cust_Street
      ,Cust_City
      ,Cust_State
      ,Cust_ZIP
      ,Inv_Date

我不明白为什么,尽管使用DISTINCT lgcustomer.cust_code以及只有MAX(inv_total),它仍然会返回该客户的每个inv_total。

我的教授说要使用UNION,但据我所知,这是为了编译两个具有相同属性的不同表...

我感谢任何可以指出我正确方向的回应!

解决方案

我们在课堂上得到的答案是使用相关的子查询和联合。

select c.cust_code
      ,cust_fname
      ,cust_lname
      ,cust_street
      ,cust_city
      ,cust_state
      ,inv_date
      ,inv_total
from lgcustomer c left outer join lginvoice i on c.cust_code = i.cust_code
where cust_state = 'AL'
and inv_total = (select max(inv_total)
                 from lginvoice i2
                 where i2.cust_code = c.cust_code)

union
select c.cust_code
      ,cust_fname
      ,cust_lname
      ,cust_street
      ,cust_city
      ,cust_state
      ,''
      ,0

from lgcustomer c left outer join lginvoice i on c.cust_code = i.cust_code
where cust_state = 'AL'
and inv_date is null
and inv_total is null
order by cust_lname asc

0 个答案:

没有答案
相关问题