1

我有一张桌子

 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 , answer nchar(20) null , )

插入 online_questionaire (username, question_id, answer) 值
('tom', 'q001' ,'d'), ('wendy', 'q09' ,'a'), ('eddy', 'q089' ,'c '), ('david', 'q001' ,'c'), ('eve', 'q001' ,'d'), ('paul', 'q001' ,'a'), ('sam', 'q001' ,'b'); 去

创建函数 [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

Go select q.Question_ID, q.Answer, count( ) as Total, count( ) * 100 / (select count(*) from online_questionaire as t where t.Question_ID = @question_id) as [Percentage] from online_questionaire as q where q .Question_ID= @question_id group by q.Question_ID, q.Answer

声明@Question_ID VARCHAR(64) = 'Q001'

SELECT * FROM QuestionFrequency(@Question_ID) AS qf

4

1 回答 1

0

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

DECLARE @Question_ID VARCHAR(64) = 'Q001'

SELECT *
FROM QuestionFrequency(@Question_ID) AS qf
于 2013-09-10T00:41:32.947 回答