查询每个客户的总和余额

时间:2014-09-19 06:47:18

标签: sql-server inner-join

我有2张表Cust_info和付款

Cust_info

cust_id,
f_name,
l_name

付款

cust_id,
c_date,
balance

现在,如果他们的余额大于0,我希望得到每个客户的余额总和。 我使用这个查询:

 SELECT payment.cust_id AS C_ID, 
        Sum(payment.balance) AS nBalance, 
        cust_info.f_name, 
        cust_info.l_name 
 FROM cust_info 
 INNER JOIN payment ON cust_info.cust_id = payment.cust_id 
 GROUP BY cust_info.f_name, cust_info.l_name 
 HAVING Sum(payment.balance)>0

此查询只返回cust_id,而我希望输出如下:

 1 - Mick - Anderson - 120

1 个答案:

答案 0 :(得分:1)

<强> QUERY

SELECT     payment.cust_id AS C_ID, 
           SUM(payment.balance) AS nBalance, 
           cust_info.f_name, 
           cust_info.l_name 
FROM       cust_info 
INNER JOIN payment 
ON         cust_info.cust_id = payment.cust_id 
GROUP BY   Payment.cust_id, cust_info.f_name, cust_info.l_name 
HAVING     (SUM(payment.balance)>0)

SQLFIDDLE

添加了payment.cust_id

的分组