Count how many variables equal a target value

All we need is an easy explanation of the problem, so here it is.

Is there a smart way to count how many variables equal some target value (in SQL Server)?

For example, if I have:

declare @a int = 1;
declare @b int = 2;
declare @c int = 1;
declare @target int = 1;

Then I’d like to do how many of @a, @b, @c eqauls @target.

In imperative languages, it’s easy to make an inline array of the variables, and then count them – for example in JS:

var a = 1, b = 2, c = 2, target = 1;
if ([a, b, c].filter(item => item == target).length == 1)
   // do something 

The equivalent in SQL of that "inline array" would be a single column table, but this would require using DECLARE TABLE, which I’d like to avoid.

Is there a similarly easy method for such counting in SQL?

Please note I’m less interested in "creating a table without declaring it" – what I really care about is the counting of variables against a target variable, so if it can be done without using tables at all, then it would be better.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

How about this solution?

declare @a int = 1;
declare @b int = 2;
declare @c int = 1;
declare @target int = 1;

FROM (VALUES (@a), (@b), (@c)) AS t(_value)
WHERE t._value = @target

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply