简体   繁体   中英

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.

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?

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 :

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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