多语句表值函数

时间:2013-09-03 15:08:11

标签: sql sql-server sql-server-2008

我有一张桌子

     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

如何计算总数和百分比?

2 个答案:

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

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