SQL中的SUM函数

时间:2012-10-30 08:22:16

标签: sql sql-server

有三个表,我们必须使用一个主键和外键从这些表中选择数据。但是在一个表中,第三个表中有很多数据。我们必须在主键的基础上对数据求和。

Table1 Table2 table3

BAl = Balance, met = Method, amo = amount, cst_id, cut_id, cut_i = customer_id

现在我们必须在同一查询中对10个cust id的方法和总和进行总结。任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:0)

如果您提供一些示例数据,则可以更轻松地编写查询来帮助您。 但是,如果您的MET字段是数字,并且您想要求它,那么您需要。

select
   t1.cst_n, t2.bal,
   sum(t3.met) as met,
   sum(t3.amo) as amo
from table1 as t1
   inner join table2 as t2 on t2.cut_id = t1.cst_id
   inner join table3 as t3 on t3.cut_i = t1.cst_id
group by t1.cst_n, t2.bal

如果您想将所有10个客户的数据汇总为一个数字,可能只需要

select
   sum(t3.met) as met,
   sum(t3.amo) as amo
from table3 as t3
where t3.cut_i in (select t.customerid from @<your variable table with cust. ids> as t)

答案 1 :(得分:0)

;WITH cte 
AS
(
    SELECT 
      *, 
      ROW_NUMBER() OVER (ORDER BY  t1.cst_id) RowNum
    FROM Table1 t1
    INNER JOIN Table2 t2 
            ON t1.cst_id = t2.cut_id
    INNER JOIN Table3 t3 
            ON t2.cut_id = t3.customer_id 
           AND t2.BAL = t3.Balance 
           AND t2.amo = t3.amount
)
SELECT SUM(*)
FROM cte
WHERE RowNum Between 1 AND 10
-- You can add a GROUP BY here