0

I have a table

     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

I want to create multi statement tabled valued function.

Let Question_id as input, I want to create table shows question_id, answer, number of answers, and percentages of answers

For example (input: Question_id = Q001)

The output will be

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

I have created function

    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

it shows me the out put

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

What should i do to count the total and percentages?

2 Answers 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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but still cannot get the percentage :)
i just changed to count() * 100 / (select count() from questions as t where.... it works :D thanks buddy
@DongminWon yep, missed that
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

2 Comments

you have to add where clause to subquery
Oh Yes, I missed that..Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.