如何使用WITH子句和select子句

时间:2015-10-29 17:51:36

标签: sql sql-server-2008

click here to view screenshot of table

问题:写一个查询来显示客户编号,名字,姓氏,这些客户的贷款总额最大,至少取自2个银行分行。

我已尝试过以下查询,但我收到此错误

  

Msg 8120,Level 16,State 1,Line 7
  专栏' customer.fname'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

代码:

with l as
(  
    select custid, sum(loan_amount) as tot 
    from loan
    group by custid 
    having count(bid) >= 2   
) 
select 
    concat(c.fname, c.ltname) as name,
    max(l.tot)
from 
    customer as c, l
where 
    l.custid = c.custid

1 个答案:

答案 0 :(得分:0)

您需要GROUP BY来选择聚合数据和非聚合数据,因此您需要决定数据的分组方式。你可以做任何一件事

SELECT CONCAT(c.fname,c.ltname) as name, MAX(l.tot)
FROM customer AS c
INNER JOIN l ON l.custid=c.custid
GROUP BY c.fname,c.ltname

SELECT CONCAT(c.fname,c.ltname) as name, MAX(l.tot)
FROM customer AS c
INNER JOIN l ON l.custid=c.custid
GROUP BY concat(c.fname,c.ltname)

请注意以下事项:

  • 我将“旧”连接语法转换为更可接受的INNER JOIN语法
  • 如果你要显示结果,你可能想要在名字和后期名称之间留一个空格。