Question: I have data in the following format:

[![I want implement this in SQL](https://i.stack.imgur.com/ayLoz.png)](https://i.stack.imgur.com/ayLoz.png)

Calculation is as follows:

* Category values are known in prior
* $U13=Q13-$T$13, $U14=Q14-$T$13 and so on.. For c1 cell value T13 remains constant.
* SUM\_C is sum of all C columns (Horizontal sum)

Also number of categories will not be known in prior. How to implement the same in SQL?

Answer: 
You want to reference the first value of `category2_numbers_r` in every row. Use `FIRST_VALUE` for this. As to adding calculated values, I suggest you calculate the separate values first and then use this result as a subquery.

```
with data as
(
  select
    category1,
    category2_numbers,
    category2_numbers_r, 
    category2_numbers - first_value(category2_numbers_r) over (order by category1) as c1,
    ... as c2,
    ... as c3,
    ... as c4,
    ... as c5
  from mytable
)
select
  category1,
  category2_numbers,
  category2_numbers_r,
  c1, c2, c3, c4, c5,
  c1 + c2 + c3 + c4 + c5 as sum_c
from data
order by category1;

```
I'll assume your table is called MyTable that has all the other columns but SUM\_C and C1

Something like this should work :

```
-- let's get your "fixed" value $T$13

declare @t13 int;
-- I don't know the exact criteria that makes T13 different from others, use the criteria in the "WHERE" clause below
SET @t13 = (SELECT TOP(1) Category2_Numbers_R FROM MyTable Where Category1 = 'A')

SELECT 
   Category1, Category2, Category2_Numbers, Category1_R, Category2_R, Category2_Numbers_R ,
   Category2_Numbers - @t13 as 'c1', -- Here is your column 'c1'
   c2, c3, c4, c5,
   Category2_Numbers - @t13 + c2 + c3 + c4 + c5 as 'SUM_C' -- Here is your column 'SUM_C'
FROM MyTable

```