I want to count the number of times people have selected a certain option in a choice field (represented as a -element with options on a webpage).
The name of choice fields are stored in the CodeType
table.
> select [CodeTypeID] from [CodeType] where [Name] = 'Favorite Fruit'
CodetypeID
----------
1000210
I can find the choices by querying the CodytypeID
-table by the found CodetypeID
:
> select [ArtifactID], [Name] from [Code] where [CodetypeID] = '1000210'
ArtifactID Name
-------------------
1039477 Apple
1039478 Pear
1039479 Banana
1039912 Peach
Each choice field has a separate table (named CodeArtifact_XXXX
where XXXX is the CodetypeID
found above). By counting the number of rows for each option (identified by CodeArtifactID
) I can see how many times a choice was selected:
> select
> count(case when [CodeArtifactID] = '1039477' then 1 else null end) as 'Apple'
> count(case when [CodeArtifactID] = '1039478' then 1 else null end) as 'Pear'
> count(case when [CodeArtifactID] = '1039479' then 1 else null end) as 'Banana'
> count(case when [CodeArtifactID] = '1039477' then 1 else null end) as 'Peach'
> from
> [CodeArtifact_1000210]
Apple Pear Banana Peach
-------------------------------
12 0 7 4
However, I have to count the choices for many more choicefields. Therefore, hardcoding all of this is not an option.
I think the only solution here is to use dynamic SQL -- something I have no experience with. Could someone give me an example of how I could count for any choicefield, the number of times their options are chosen?
I other words: by only changing the choicefield [Name]
in the beginning (Favorite Fruit
, 'Marital Status', 'Latest Diploma', etc), the choices should be looked up and counted automatically.
Is this possible? Any help would be greatly appreciated.