简体   繁体   English

如何在没有分组依据的情况下对SQL中的两列求和

[英]How to sum two columns in sql without group by

I have columns such as pagecount, convertedpages and changedpages in a table along with many other columns. 我在表格中还有许多列,例如页数,转换页和更改页。

pagecount is the sum of convertedpages and changedpages. pagecount是已转换页面和已更改页面的总和。

I need to select all rows along with pagecount and i cant group them. 我需要选择所有页面行数以及我不能将它们分组。 I am wondering if there is any way to do it? 我想知道是否有任何办法可以做到?

This select is part of view. 此选择是视图的一部分。 so can i use another sql statement to bring just the sum and then somehow make it part of the main sql query? 所以我可以使用另一个sql语句仅带总和,然后以某种方式使其成为主要sql查询的一部分吗?

Thank you. 谢谢。

SELECT
   *,
   (ConvertedPages + ChangedPages) as PageCount
FROM Table

If I'm understanding your question correctly, while I'm not sure why you can't use group by , another option would be to use a correlated subquery : 如果我正确理解了您的问题,但不确定为什么不能使用group by ,另一种选择是使用correlated subquery

select distinct id, 
       (select sum(field) from yourtable y2 where y.id = y2.id) summedresult
from yourtable y

This assumes you have data such as: 假设您具有以下数据:

id  |  field
1   |  10
1   |  15
2   |  10

And would be equivalent to: 相当于:

select id, sum(field)
from yourtable
group by id

Not 100% on what you're after here, but if you want a total across rows without grouping, you can use OVER() with an aggregate in SQL Server: 不是您要执行的操作的100%,但是如果您希望跨行总计而不进行分组,则可以将OVER()与SQL Server中的聚合一起使用:

SELECT *, SUM(convertedpages) OVER() AS convertedpages
     , SUM(changedpages) OVER() AS changedpages
     , SUM(changedpages + convertedpages) OVER() as PageCount
FROM Table

This repeats the total for every row, you can use PARTITION BY inside OVER() if you'd like to have the aggregate to be grouped by some fields while still displaying the full detail of all rows. 这将重复每一行的总计,如果您希望在某些字段中对聚合进行分组,同时仍显示所有行的详细信息,则可以在OVER()使用PARTITION BY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM