从公用表表达式中选择创建函数

时间:2017-10-25 01:34:31

标签: sql sql-server function common-table-expression

我需要从一个复杂的查询创建函数,该查询从主表生成临时表,根据条件在某个值中进行减法。临时表为setonesettwosetthree,主表称为main。查询如下。

with
    setone
    AS
        (SELECT type_id
              , time
              , id
              , type
           FROM main
          WHERE type = 0),
    settwo
    AS
        (SELECT type_id
              , time
              , id
              , type
           FROM main
          WHERE type = 1),
    setthree
    AS
        (SELECT setone.*
              , (SELECT max(time)
                   FROM settwo
                  WHERE settwo.id = setone.id
                    AND settwo.time < setone.time)
                    AS off
           FROM setone)
  SELECT id, SUM (off - time) / COUNT (*) MEAN
    FROM setthree
GROUP BY id

现在,查询的结果是名为MEAN的值,如何根据传递idtime的查询创建函数,然后返回值MEAN。 功能看起来像是  dbo.[FunctionGetMEAN](id,time) as MEAN

预期结果的示例:

id  time    mean
222   1     0.3
333   1     0.7
222   2     0.8

1 个答案:

答案 0 :(得分:0)

阿。你可能想要的是一个存储过程。查找创建过程。基本语法就是这样..

Create procedure dbo.procedurename 
( @id int 
, @time int) 

As 

Begin
  • 您的查询*

其中声明需要包括在

之前
Where 

Id = @id 
And time = @time 

最后一句话必须是:

End

然后您可以像这样调用yiur存储过程。

Exec dbo.yourprocedure 1, 100