Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

SQL Server Management Studio – Retrieve one parent row regardless of number of children when filtering on children

Let’s say you want to report on each parent row, but must join a child row to do filtering on the child row, but you only want to return one row per parent. The following SQL will not work, but instead repeats the parent row per number of children filtered on.

select a.test_name, b.question_type
 from tests a
 join test_questions b on b.test_guid = a.test_guid 
 where a.test_name like 'Exodus 1 - 5%'
   and b.question_type = 'Multiple Choice'

The above result reflects that there are 12 multiple choice questions (child of tests table) for every parent test (tests table) where the test name is like ‘Exodus 1 – 5%’. What I want to accomplish is to simply have the results reflect how many tests are there that have a multiple choice question.

To accomplish this, we must instead join the questions table as a sub select using ROW_NUMBER OVER PARTITION BY method where the rownumber = 1 to ensure that we only retrieve 1 child one, hence one parent row.

select a.test_name, b.question_type
   from tests a
 join (select test_questions.test_guid, test_questions.question_type, ROW_NUMBER() OVER (PARTITION BY test_questions.test_guid order by test_questions.test_guid) As RowNumber
         from test_questions
        where test_questions.question_type = 'Multiple Choice') b on a.test_guid = b.test_guid
  where rownumber = 1
   and a.test_name like 'Exodus 1 - 5%'

Leave a Reply