在MSSQL中的VIEW上使用Sum(Case)时动态SUM()

时间:2013-06-03 14:23:46

标签: sql sql-server dynamic

我正在尝试创建一个VIEW,其中我应该有以下列:

Clinic_id | Result_month_id | AVF | AVC | AVG |其他| Total_Days

Total_Days应使用(AVF + AVC + [AVG] +其他)动态计算。

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上创建的四列的总和?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

答案 2 :(得分:1)

在视图上创建视图:

CREATE VIEW Rate AS ...

CREATE VIEW Rate_All AS
SELECT *, AVC + [AVG] + Other as TotalDays
FROM Rate;