多语句表值函数计算/显示百分比

时间:2013-09-10 00:17:30

标签: sql

我有一张桌子

 UserName  Question_ID  Answer
  Tom       Q001           D
  Wendy     Q009           A
  Eddy      Q089           C
  David     Q001           C
  Eve       Q001           D
  Paul      Q001           A
  Sam       Q001           B
  Tom       Q002           B
  Tom       Q003           C

我想创建多语句表值函数。

让Question_id作为输入,我想创建表格显示question_id,答案,答案数量和答案百分比

例如(输入:Question_id = Q001)

输出

  Question_ID Answer Total Percentage
    Q001          A      1       20
    Q001          B      1       20
    Q001          C      1       20
    Q001          D      2       40

我在下面创建了一个函数示例:

create function [dbo].[QuestionFrequency]
(
@question_id varchar(10)    
)

Returns @frequency table (question_id varchar(10), answer varchar(10))
As 
begin

insert @frequency (question_id, answer)
select question_Id, Answer from questions where @question_id = Question_id
return 
end

目前此代码对我没有显示任何内容?

我也有这个来计算百分比,但我的问题是,如何获得用户输入?运行功能?

这是代码:

创建表[online_questionaire] (username nchar(10)null,
 question_id nchar(20)null,  回答nchar(20)null,)

插入online_questionaire(用户名,question_id,answer) 值
('汤姆','q001','d'), ('wendy','q09','a'), ('eddy','q089','c'), ('david','q001','c'), ('前夕','q001','d'), ('paul','q001','a'), ('sam','q001','b');  GO

创建函数[dbo]。[QuestionFrequency]     (           @question_id varchar(10)
    )

Returns @frequency table (question_id varchar(10), answer varchar(10))
As 
begin

insert @frequency (question_id, answer)
select question_Id, Answer from online_questionaire where @question_id = Question_id
return 
end

转到     选择     q.Question_ID,q.Answer,     将()计为总计,     count()* 100 /(从online_questionaire选择count(*)为t,其中t.Question_ID = @question_id)为[Percentage] 来自online_questionaire作为q 其中q.Question_ID = @question_id 按q.Question_ID分组,q.Answer

DECLARE @Question_ID VARCHAR(64)='Q001'

SELECT * 来自QuestionFrequency(@Question_ID)AS qf

1 个答案:

答案 0 :(得分:0)

这是调用上面的表值函数的方法:

DECLARE @Question_ID VARCHAR(64) = 'Q001'

SELECT *
FROM QuestionFrequency(@Question_ID) AS qf