如何在SQL中获取具有相同id和不同表的列的总和?

时间:2015-07-24 08:59:17

标签: sql sql-server

我有2个以下表结构 首先是这样的

if

和第二个表(我想要更新)是这个

szCustId    szArClassId    decCreditLimit   szPaymentTermId
22101100071    AMORE        0.00            30 HARI_AMORE    
22101100071    BELLISIMO    500.00          17 HARI_BELLISIMO
22101100071    CAPE         0.00            17 HARI_CAPEDISC
22101100071    FOOD         0.00            17 HARI_FOOD
22101100071    GFES         1000.00         0 HARI_GFES
22101100071    GILBEYS      0.00            17 HARI_GILBEYS
22101100071    GZERO        0.00            13 HARI_GZERO
22101100071    AMORE        0.00            30 HARI_AMORE    
22101100069    BELLISIMO    500.00          17 HARI_BELLISIMO
22101100069    CAPE         0.00            17 HARI_CAPEDISC
22101100069    FOOD         0.00            17 HARI_FOOD
22101100888    FOOD         0.00            17 HARI_FOOD
22101100888    GFES         1000.00         0 HARI_GFES
22101100888    GILBEYS      0.00            17 HARI_GILBEYS
22101100888    GZERO        0.00            13 HARI_GZERO

我需要根据特定szCustId bAllowToCredit decCreditLimit 22101100071 1 0.00 22101100069 1 0.00 22101100888 1 0.00

获取decCreditLimit匹配或分组的总和

所以结果(表2中)就像这样

szCustId

如何编写此SQL查询?

5 个答案:

答案 0 :(得分:1)

您可以join两个表并使用sum汇总函数和group by子句来计算每个decCreditLimitszCustId的总bAllowToCredit

select t2.szCustId
     , t2.bAllowToCredit
     , sum(t1.decCreditLimit) as decCreditLimit 
from table1 t1
join table2 t2 on t1.szCustId = t2.szCustId
group by t2.szCustId
       , t2.bAllowToCredit

答案 1 :(得分:0)

尝试此查询

select a.szCustId,a.bAllowToCredit,b.decCreditLimit  from tablesecond a
join(
select szCustId,sum(decCreditLimit) as decCreditLimit  from tablefirst)b
on a.szCustId=b.szCustId

答案 2 :(得分:0)

UPDATE t2 SET t2.decCreditLimit = (SELECT SUM(decCreditLimit) 
                                   FROM Table1 t1
                                   WHERE t1.szCustId = t2.szCustId)
FROM Table2 t2

答案 3 :(得分:0)

一个简单的分组将执行任务 -

SELECT t2.szCustId
     , t2.bAllowToCredit
     , sum(t1.decCreditLimit)
FROM table1 t1
INNER JOIN table2 t2 ON t1.szCustId = t2.szCustId
GROUP BY t2.szCustId
       , t2.bAllowToCredit

答案 4 :(得分:0)

首先从第一个表计算列总和,然后像这样在seconde表上更新。 Update t2 Set t2.decCreditLimit = t1.Sum_Column From Table2 t2 ( Select szCustId,Sum(t1.decCreditLimit) as Sum_Column From Table1 t1 group by t1.szCustId )A where A.szCustId = t2.szCustId