skip to Main Content

I have a table like this

enter image description here

How can i add new column with the value of column is the total value of price column with the same no_btsc like this

enter image description here

i use SUM but its no use. what SQL script i can use with case like this??

i use sum in nested query like this

Select id, name, price, no_btsc, (select SUM(price) from table1 group by no_btsc) 
from table 1

3

Answers


  1. You can try it by doing this:

    SELECT id, price, name, btus_no, SUM(price) OVER (PARTITION BY btus_no) AS total_price   
    FROM table1
    
    Login or Signup to reply.
  2. you can solve this using windows function but you not need to use partition by because you need sum of all the values present in the column

    SELECT id, price, name, no_btsc, SUM(price) OVER () AS total_price   
    FROM t1;
    

    if you are looking sum with respective to some values (kind of groups) then you can use partition by in the query

    SELECT id, price, name, no_btsc, SUM(price) OVER (partition by columns_name) 
    AS total_price FROM t1;
    
    Login or Signup to reply.
  3. Another way of doing it is by using cross join to add a value to each row like this:

    SELECT [id], [price], [Name], [btsc_no], [t2].[sum] FROM t1 CROSS APPLY (SELECT SUM([PRICE]) as sum FROM @Table) AS t2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search