2015-02-12 6 views
1

У меня есть stored procedure, в котором у меня есть 2 переменныеКак сделать случай, когда лучше в SQL

Declare @from int 
Declare @to int 

Эти переменные будут давать месяц от и для расчета по математике.

Моя таблица выглядит так:

sum1/sum2/sum3/Sum4/Sum5/Sum6/Sum7/Sum8/Sum9/Sum 10/Sum 11/Sum 12/GroupByID

И я расчет в моем SQL, как это:

Select SUM(SUM1) + SUm(Sum2) + .... + Sum(Sum12) from Table group by GroupByID 

Теперь я хочу только Sum(month) месяца, который дается в parameters, как это сделать?

+1

Это действительно плохой дизайн. –

+0

Не от меня ... происходит из веб-сервиса SAP, мне только нужно обрабатывать это – Kovu

+0

Какие dbms? (Не похож на ANSI SQL ...) – jarlh

ответ

2

Вы должны использовать Dynamic Query

DECLARE @from INT=1 
DECLARE @to INT=5, 
     @cnt INT, 
     @sql NVARCHAR(max) 

SET @[email protected] 
SET @sql='select ' 

WHILE @cnt <= @to 
    BEGIN 
     SET @sql += 'sum(sum' + CONVERT(VARCHAR(50), @cnt) + '),' 
     SET @cnt+=1 
    END 

SELECT @sql = LEFT(@sql, Len(@sql)-1)+ ' from tablename group by GroupByID' 

exec sp_executesql @sql 
+0

Немного комментариев: вы можете удалить одну переменную '@ from' и назначить 1 на' @ cnt' –

+0

@GiorgiNakeuri - это не всегда будет '1'. Это вход. –

+0

Затем используйте '@ from' вместо' @ cnt'. –

0

Вы должны проверить @to и @from для каждого месяца и применить связанную месяц столбец в выражении суммы, если в диапазоне:

Select 
    GroupByID, 
    SUM(
    case when 1 between @to and @from then coalesce(Sum1,0) else 0 end + 
    case when 2 between @to and @from then coalesce(Sum2,0) else 0 end + 
    case when 3 between @to and @from then coalesce(Sum3,0) else 0 end + 
    case when 4 between @to and @from then coalesce(Sum4,0) else 0 end + 
    case when 5 between @to and @from then coalesce(Sum5,0) else 0 end + 
    case when 6 between @to and @from then coalesce(Sum6,0) else 0 end + 
    case when 7 between @to and @from then coalesce(Sum7,0) else 0 end + 
    case when 8 between @to and @from then coalesce(Sum8,0) else 0 end + 
    case when 9 between @to and @from then coalesce(Sum9,0) else 0 end + 
    case when 10 between @to and @from then coalesce(Sum10,0) else 0 end + 
    case when 11 between @to and @from then coalesce(Sum11,0) else 0 end + 
    case when 12 between @to and @from then coalesce(Sum12,0) else 0 end 
    ) as total 
from Table 
group by GroupByID; 
Смежные вопросы