-4

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

表格1 表2 表3

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

现在我们必须对同一个查询中的 10 个客户 ID 的方法和总和进行求和。谁可以帮我这个事?

4

2 回答 2

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)
于 2012-10-30T08:25:08.147 回答
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
于 2012-10-30T08:31:15.170 回答