0

我有一张桌子

     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

它向我展示了输出

Question_ID     Answer
Q001           D
Q001           C
Q001           D
Q001           A
Q001           B

我应该怎么做才能计算总数和百分比?

4

2 回答 2

1
select
    q.Question_ID, q.Answer,
    count(*) as Total,
    count(*) * 100 / (select count(*) from questions as t where t.Question_ID = @question_id) as [Percentage]
from questions as q
where q.Question_ID= @question_id
group by q.Question_ID, q.Answer
于 2013-09-03T15:13:16.683 回答
0
SELECT
Question_ID,
Answer,
COUNT(*) TotaL_Answers,
(COUNT(*) / CONVERT(DECIMAL(2),(select COUNT(*) from TABLE_NAME where Question_ID= 'Q001')))*100 'Percent'
FROM TABLE_NAME
WHERE Question_ID= 'Q001'
GROUP BY Question_ID, Answer
于 2013-09-03T15:24:51.093 回答