我有一张这样的表格(总结客户,每个人都有一些付款):
customerID Payments InvoicCode
1 1000 112
1 250 456
2 100 342
1 20 232
2 500 654
3 300 230
我想要的是下面(每行客户付款的总和):
customerID Payments InvoicCode SumPayment
1 1000 112 1270
1 250 456 1270
2 100 342 600
1 20 232 1270
2 500 654 600
3 300 230 300
答案 0 :(得分:5)
在多行中复制更宽范围的数据是不正常的正常形式。考虑更新付款或添加新客户付款的影响 - 您必须更新该客户的所有相关总计。
创建一个视图/存储过程会更简单,它可以在运行时为您提供总计,您可以在需要时调用它们:
create view CustomerTotals as
select customerID
,sum(Payments) as SumPayment
from mytable
group by customerID
然后你可以用select * from CustomerTotals
引用它,输出如下:
customerID SumPayment
1 1270
2 600
3 300
答案 1 :(得分:5)
这是:
SELECT t.customerID,
t.Payments,
t.InvoicCode,
aux.SumPayment
FROM tablename t
INNER JOIN
(SELECT customerID,
SUM(Payments) as SumPayment
FROM tablename
GROUP BY customerID) aux ON t.customerID = aux.customerID
答案 2 :(得分:4)
试试这个,(主要适用于任何rdbms )
SELECT a.*, b. totalPayment
FROM paymentsTable a
INNER JOIN
(
SELECT customerID, SUM(Payments) totalPayment
FROM paymentsTable
GROUP BY customerID
) b ON a.customerID = b.customerID
答案 3 :(得分:3)
select t1.*,sumPay
from table t1,
(select customerID,sum(Payments) as sumPay
from table
group by customerID) t2
where t1.cutomerID=t2.customerID
答案 4 :(得分:3)
您可以创建视图或尝试这样的选择:
SELECT customerID,
Payments,
InvoicCode,
(SELECT SUM(Payments)
FROM Customer IC
WHERE IC.customerID = OC.customerID )
FROM Customer OC
答案 5 :(得分:3)
将表格加入其自身的总和版本:
select mytable.customerID, Payments, InvoicCode, SumPayment
from mytable
join (select customerID, sum(Payments) as SumPayment from mytable group by 1) x
on x.customerID = mytable.customerID
答案 6 :(得分:3)
您可以使用子查询获取总和,然后将其与表格连接以添加其他列。
SELECT x2.customerID
, x2.payments
, x2.invoice
, x1.sumpayment
FROM
(
select customerID
,sum(Payments) as SumPayment
from yourtable
group by customerID
) x1
inner join yourtable x2
ON x1.customerID = x2.customerid
答案 7 :(得分:2)
对于MSSQL
SELECT Т1.*, Т2.SumPayment
FROM TableName T1 INNER JOIN
( SELECT customerId, SUM(Payments) SumPayment
FROM TableName
GROUP BY customerID
) T2 ON T1.customerID = T2.customerId
答案 8 :(得分:2)
假设您的dbms是MS Sql-Server,您可以使用带有OVER
子句的SUM(Payments)
:
SELECT customerID, Payments,InvoicCode
,SumPayment=SUM(Payments)OVER(PARTITION BY customerID)
FROM t
SQL-Fiddle:http://sqlfiddle.com/#!3/2ac38/2/0
答案 9 :(得分:2)
SELECT
t.customerID as customerID,
t.Payments as Payments,
t.InvoicCode as InvoicCode,
total as SumPayment
FROM
theTable t,
(
SELECT customerId,
sum(Payments) as total
FROM theTable
GROUP BY customerId
) tmp
WHERE
tmp.customerId = t.customerId