32

我已经读过(this),但无法找到一种方法来解决我的具体问题。我知道这SUM()是一个聚合函数,不这样使用它是没有意义的,但在这种特定情况下,我必须SUM()在保持每一行的同时获得所有结果。

这是表格:

--ID-- --amount--
  1        23
  2        11
  3        8
  4        7

我需要SUM()数量,但保留每条记录,所以输出应该是:

--ID-- --amount--
  1        49
  2        49
  3        49
  4        49

我有这个查询,但它只对每一行求和,而不是所有结果:

SELECT 
    a.id,
    SUM(b.amount)

FROM table1 as a 
JOIN table1 as b ON a.id = b.id
GROUP BY id

没有SUM()它只会返回一行,但我需要维护所有 ID...

注意:是的,这是一个非常基本的示例,我可以在这里使用 php 来执行此操作,但显然表格更大并且具有更多行和列,但这不是重点。

4

5 回答 5

21
SELECT a.id, b.amount
FROM table1 a
CROSS JOIN
(
    SELECT SUM(amount) amount FROM table1
) b

您需要将表中每一行的总和值与 each执行笛卡尔连接id。由于 subselect ( ) 只有一个结果49,因此它基本上只是被附加到每个id.

于 2012-07-06T07:31:17.490 回答
15

MS SQL你可以 使用OVER()

 select id, SUM(amount) OVER()
 from table1;

select id, SUM(amount) OVER()
from (
  select 1 as id, 23 as amount
  union all
  select 2 as id, 11 as amount
  union all
  select 3 as id, 8 as amount
  union all
  select 4 as id, 7 as amount
) A

在此处输入图像描述

--- OVER PARTITION ID

PARTITION BY例如,当您想SUM()按月执行或按季度报告销售额或按年度进行报告时,这非常有用......(注意需要distinct它对所有行都执行)

 select distinct id, SUM(amount) OVER(PARTITION BY id) as [SUM_forPARTITION]
 from (
     select 1 as id, 23 as amount
     union all
     select 1 as id, 23 as amount
     union all
     select 2 as id, 11 as amount
     union all
     select 2 as id, 11 as amount
     union all
     select 3 as id, 8 as amount
     union all
     select 4 as id, 7 as amount
) OverPARTITIONID

在此处输入图像描述

于 2015-09-11T02:53:14.147 回答
6

使用子查询将原始表连接到总和:

SELECT * FROM table1, (SELECT SUM(amount) FROM table1 AS amount) t
于 2012-07-06T07:29:28.347 回答
0

这仅执行一个sum()查询,因此它应该执行正常:

SELECT a.id, b.amount
FROM table1 a
cross join (SELECT SUM(amount) as amount FROM table1 AS amount) b
于 2012-07-06T07:35:03.820 回答
0

如果其他人有同样的问题并且没有加入,我们可以执行以下操作

select *
,totcalaccepted=(select sum(s.acceptedamount)  from cteresult s)
, totalpay=(select sum(s.payvalue)  from cteresult s)     
from cteresult  t
end
于 2021-04-21T03:32:35.343 回答