Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL : Count with "==" to check in SQL Server

I’m working with SQL Server and I want to create a view (my_View) which has these columns :

[element_1]
[element_2]
[element_3]
[element_4]

All of them are referring to the same column, named [parent_1], in another table (AT)

[parent_1] can have 4 possible values [value_1], [value_2], [value_3] and [value_4].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I want is that, using COUNT,

  • [element_1] is equal to the number of times that [parent_1] is equal to [value_1]
  • same for [element_2], [element_3] and [element_4] equals to [value_2], [value_3] and [value_4].

Is it possible to use "==" inside the COUNT to see if it checks the criteria?

Something like this:

COUNT (AT.parent_1 == "value_1") AS element_1
COUNT (AT.parent_1 == "value_2") AS element_2
COUNT (AT.parent_1 == "value_3") AS element_3
COUNT (AT.parent_1 == "value_4") AS element_4

Thanks guys

>Solution :

You can use the CASE instruction for that

https://docs.microsoft.com/fr-fr/sql/t-sql/language-elements/case-transact-sql?view=sql-server-ver15

SUM (CASE WHEN AT.parent_1 = 'value_4' THEN 1 ELSE 0 END) as element_4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading