1

我正在尝试创建一个视图,其中应该包含以下列:

Clinic_id | 结果_月_id | 视音频 | AVC | 平均 | 其他 | Total_Days

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

但以上没有奏效。知道如何动态创建我在 VIEW 上创建的四列的总计吗?

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 回答
1

您可以为此使用子查询:

CREATE VIEW Rate AS 
select t.*, AVC + [AVG] + Other as TotalDays
from (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
     ) t
于 2013-06-03T14:40:40.003 回答