Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL中的SUM函数_Sql_Sql Server - Fatal编程技术网

SQL中的SUM函数

SQL中的SUM函数,sql,sql-server,Sql,Sql Server,有三个表,我们必须使用一个主键和一个外键从这些表中选择数据。但是在一个表中,在第三个表中有很多数据。我们必须根据主键对数据求和 现在,我们必须根据方法求和,并在同一查询中求和10个客户id。有人能帮我吗?如果您提供一些示例数据,编写查询来帮助您会更容易。 但是,如果您的MET字段是数字字段,并且您想对其求和,那么您需要 select t1.cst_n, t2.bal, sum(t3.met) as met, sum(t3.amo) as amo from table1 as

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


现在,我们必须根据方法求和,并在同一查询中求和10个客户id。有人能帮我吗?

如果您提供一些示例数据,编写查询来帮助您会更容易。 但是,如果您的
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)
选择
满足时的总和(t3.met),
金额(t3.amo)为amo
表3中的t3
其中t3.cut_i in(从@as t中选择t.customerid)

@MahmoudGamal这就是我显示表中scema的原因我必须同时选择10个客户,它将只为一个客户提供。。。。我要求在一个查询中为10个客户提供相同的测试数据。这个查询通过
cst_n
(假定的客户编号)@Ashishsingh对客户进行分组-我使用它,只是为了可读性和分页,让您每次为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)
;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