Question

Hello what I want is to write a query which will fetch me 3 column:-

  1. nvarchar column1
  2. integer Values column2
  3. single cell of the summed column2

is it possible , I am getting the following error:-

Msg 8120, Level 16, State 1, Line 1 Column 'tablename.columnname' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

What is the correct procedure to get data in the format I wish to get.

Edit

Jaques' answer works but I dont get what I want. What I want is:

column 1 PID | column 2 SID | column 3 | column 4 | Column 5(Total of 4)
-------------------------------------------------------------------------
1            | 1            | ABC      | 125.00   | 985.00
2            | 2            | XYZ      | 420.00   |
3            | 3            | DEF      | 230.00   |
4            | 4            | GHI      | 210.00   |
Was it helpful?

Solution 2

You can do it in the following way, because you need to add all non aggregated values in the group by, which makes it difficult

Select column1, column2, SUM(column2) OVER (PARTITION BY column1) as Total from [Table]

This should work.

You can do it with a subselect from your edited answer, but why do you want it like that?

Select Column1, Column2, Column3, Column4, (Select SUM(Column4) from Table) as Column 5 from Table

OTHER TIPS

i suspect you are using some aggregate function on some columns and not listing your remaining columns in group by clause. your query should look like this.

select sum(column2), column1 from table1
group by column1

You must include the same columns in the select and group by clauses.

If you want to sum a column with all the values, you must include in the select clause a column with different value for each row, like this:

SELECT columnId, sum(column4) as total
FROM MyTable
GROUP BY columnId

or simply don't include on the select any extra column, like this:

select sum(column4) from MyTable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top