Obtain information from a row if it meets certain criteria

88 Views Asked by At

Okay so the overall scope of the problem is I'm using a table valued function so SSRS can create various reports off the data and then I used another program to stitch all those reports together. So anyway the problem is that I need to obtain a column's value IF another column within that row contains a certain value. Then after adding that value to another place a new value back into a column of a database row so that other reports and use that data. So for example:

RETURNS @ReportTable table
(
str_beta_group varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, 
str_alpha_group varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, 
str_group varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, 
debit decimal(24, 6) NULL, 
credit decimal(24, 6) NULL,
    credit_total decimal(24,6) NULL

)

I'm new to database development and I've tried various ways I can't figure out how to get the syntax correct and I always end up with errors. So based on the table above how would I write this logic with T-Sql syntax:

 decimal epsilon_temp, gamma_temp;
  if(str_group='epsilon')
 {
epsilon_temp = credit; --the credit from that row where str_group = epsilon 
 }
 else if(str_group='gamma')
 {
gamma_temp = credit; --the credit from that row where str_group = gamma
 }
 --Then after that UPDATE
 UPDATE @ReportTable
SET credit_total = SUM(epsilon_temp + gamma_temp )
WHERE str_group = epsilon
1

There are 1 best solutions below

1
On

I am taking a guess at what You need. Is this about how to get sums out of data and grouping the results by str_group? How does this look:

SELECT
  CASE WHEN str_group is NULL THEN 'TOTAL' ELSE str_group END str_group
  SUM(credit) credit
FROM 
  table
GROUP BY GROUPING SETS 
  ((),(str_group))