1

次の列が必要なビューを作成しようとしています。

クリニック ID | Result_month_id | AVF | AVC | 平均 | その他 | 合計_日

Total_Days は、(AVF+AVC+[AVG]+Other) を使用して動的に計算する必要があります。

SQL クエリは次のとおりです。

CREATE VIEW Rate AS 

SELECT  
clinic_id, result_month_id, 
sum(case v_id when 'ula' then [days] else 0 end) as AVF,
sum(case v_id 
        when 'ter' then [days] 
        when 'theter' then [days] 
        when 'p_theter' then [days] 
        when 't_theter' then [days] 
        else 0 
    end) as AVC,
sum(case v_id when 's_graft' then [days] else 0 end) as [AVG],
sum(case v_id when 'other' then [days] else 0 end) as [Other] 

FROM [Server].[DBName].[TableName]

GROUP BY clinic_id, result_month_id
;

を使用して最後の列を追加しようとしました

  SELECT 
   columns,
   .... 
   (AVF+AVC+[AVG]+Other)as Total_Days

  FROM
  (SELECT 
       the QUERY displayed above...
  )q

しかし、上記はうまくいきませんでした。ビューで作成している4つの列の合計を動的に作成するにはどうすればよいですか?

4

3 に答える 3

3

最も簡単な方法は、CTE を使用することです。

CREATE VIEW Rate AS 

WITH CalculatedValues AS (
    SELECT  
        clinic_id, result_month_id, 
        sum(case v_id when 'ula' then [days] else 0 end) as AVF,
        sum(case v_id 
                when 'ter' then [days] 
                when 'theter' then [days] 
                when 'p_theter' then [days] 
                when 't_theter' then [days] 
                else 0 
            end) as AVC,
        sum(case v_id when 's_graft' then [days] else 0 end) as [AVG],
        sum(case v_id when 'other' then [days] else 0 end) as [Other] 
    FROM [Server].[DBName].[TableName]
    GROUP BY clinic_id, result_month_id
    )
SELECT *, (AVF+AVC+[AVG]+Other)as Total_Days
FROM CalculatedValues;
于 2013-06-03T14:44:39.390 に答える
1

ビューにビューを作成します。

CREATE VIEW Rate AS ...

CREATE VIEW Rate_All AS
SELECT *, AVC + [AVG] + Other as TotalDays
FROM Rate;
于 2013-06-03T14:46:10.263 に答える