Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 query Question

Author  Topic 

pablowilks
Starting Member

6 Posts

Posted - 2012-05-28 : 15:44:56
is it best to do joins or subqueries? my thinking is always joins. However I have there are instances when subqueries. anybody have any thoughts on that?





flamblaster
Constraint Violating Yak Guru

384 Posts

Posted - 2012-05-28 : 16:53:50
You might want to think about re-designing your tables to allow for a marriageid and have husbandid/wifeid as foreign keys from another table. That being said, I think you can accomplish what you're looking for by doing this:

declare @Marriage table (Husband_Id int, Wife_Id int, State char(2), City Varchar(30), MarriageDate date)
insert into @Marriage (Husband_id, Wife_Id,State, City, MarriageDate)
values
(1, 1, 'CO', 'Fort Collins', '2011-01-01'),
(1, 2, 'CO', 'Fort Collins', '2012-01-01'),
(2, 3, 'CO', 'Fort Collins', '2011-01-01'),
(3, 5, 'CO', 'Fort COllins', '2011-01-01'),
(3, 7, 'CO', 'Fort COllins', '2012-01-01')

EDIT:

If you want the total number of men that have been married twice or more, and not the particular men, you'd do this:
select COUNT(distinct husband_id) as NumMen
from (
select Husband_Id, COUNT(*) as NumTimesMarried
from @Marriage
group by Husband_Id
having COUNT(*)>1) A

Go to Top of Page

pablowilks
Starting Member

6 Posts

Posted - 2012-05-28 : 19:48:40
Thanks flamblaster. Is the capital a at the end a mistake?
Go to Top of Page

flamblaster
Constraint Violating Yak Guru

384 Posts

Posted - 2012-05-28 : 19:56:26
Welcome...and do you mean the "A"? If so, no, it's an alias for the subquery. Without aliasing the subquery, you'd receive an error.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-29 : 01:26:08
quote:
Originally posted by pablowilks

Thanks flamblaster. Is the capital a at the end a mistake?



its just a short name for the derived table he created out of query called as alias

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-31 : 15:23:34
quote:
Originally posted by pablowilks

is it best to do joins or subqueries? my thinking is always joins. However I have there are instances when subqueries. anybody have any thoughts on that?








why did you update original thread with new question?
you should be posting this as a new thread!

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -