使用SUM()不进行分组的结果(Using SUM() without grouping the r

2019-06-26 02:10发布

我已经阅读(这一点) ,但不能想出一个办法来实现它向我的具体问题。 我知道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来这里做到这一点,但显然该表是更大,有更多的行和列,但是这不是问题的关键。

Answer 1:

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

您需要执行一个笛卡儿连接每一行的表中的每个总和值的id 。 由于只有一个子选择(的结果49 ),它基本上只是被上涨到每个id



Answer 2:

与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分区ID
当你想要做的每月SUM(),例如或做季报销售或每年PARTITION BY这是非常有用的。(注不同需要它做的所有行)

 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



Answer 3:

加入原始表与子查询的总和:

SELECT * FROM table1, (SELECT SUM(amount) FROM table1 AS amount) t


Answer 4:

这不只是一个sum()查询,所以应该进行确定:

SELECT a.id, b.amount
FROM table1 a
cross join (SELECT SUM(amount) as amount FROM table1 AS amount) b


文章来源: Using SUM() without grouping the results
标签: mysql sum