sql server - Difference in output from two SQL queries -
what difference between 2 sql queries below other query2 returning additional field? there possible scenarios output of 2 queries different (other additional field in query2)
query1:
select field1, count(*) table1 group field1 having count(*) > 1
query2:
select field1, field2, count(*) table1 group field1, field2 having count(*) > 1
absolutely, these different. query2's group clause specifies field. means when results aggregated, aggregated combined unique values of field1 , field2. is, 2 records aggregated if , if both field1 , field2 equal.
for example:
select profession, count(*) people group profession having count(*) > 1
will return list of professions associated counts like:
software developer, 10 pm, 5 tester, 2
whereas:
select profession, gender, count(*) people group profession, gender having count(*) > 1
will return list of professions broken out gender like:
software developer, male, 5 sofware developer, female, 5 pm, male, 3 pm, female, 2 tester, male, 2
edit additional requested information:
you can retrieve counts of professions rows both genders via:
select profession, count(*) people group profession having sum(case gender when 'female' 1 else 0 end) > 0 , sum(case gender when 'male' 1 else 0 end) > 0
it gets bit hairy (need subqueries) if need associated gender counts
Comments
Post a Comment