944,204 Members | Top Members by Rank

Ad:
  • MS SQL Discussion Thread
  • Marked Solved
  • Views: 1173
  • MS SQL RSS
Oct 19th, 2009
0

Select only items that don't exist in another table

Expand Post »
I want to select from a table only when a field repeats more than once. For this I have:

MS SQL Syntax (Toggle Plain Text)
  1. SELECT title, Count(*) AS Cnt FROM poss_titles WHERE Cnt > 1 GROUP BY Title ORDER BY Cnt DESC

But it says invalid column name cnt. How should I refer to this dynamic field?
Also, I only really want titles which dont exist in another table. I believe a left join is required for this but I'm not too sure how to do it.
Can anyone offer me some pointers?
Similar Threads
Reputation Points: 9
Solved Threads: 0
Light Poster
benkyma is offline Offline
34 posts
since Sep 2009
Oct 19th, 2009
3
Re: Select only items that don't exist in another table
You can't use the alias in the boolean test plus you should use a having clause to test the count(*) and not the where clause.

sql Syntax (Toggle Plain Text)
  1. SELECT title, count(*) As Cnt
  2. FROM poss_titles
  3. GROUP BY title
  4. HAVING count(*) > 1
  5. ORDER BY count(*) desc

as for only showing fields that don't exist in another table you can use exists condition.

sql Syntax (Toggle Plain Text)
  1. SELECT title, count(*) As Cnt
  2. FROM poss_titles pt
  3. WHERE NOT EXISTS (SELECT title FROM other_table ot WHERE ot.title = pt.title)
  4. GROUP BY title
  5. HAVING count(*) > 1
  6. ORDER BY count(*) desc
Last edited by cgyrob; Oct 19th, 2009 at 3:04 pm.
Reputation Points: 91
Solved Threads: 18
Junior Poster
cgyrob is offline Offline
125 posts
since Sep 2008
Oct 20th, 2009
0
Re: Select only items that don't exist in another table
That's fantastic. Thanks a lot : )
Reputation Points: 9
Solved Threads: 0
Light Poster
benkyma is offline Offline
34 posts
since Sep 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in MS SQL Forum Timeline: SELECT statement
Next Thread in MS SQL Forum Timeline: Best way to backup a database from one server to another server in SQL Server 2005





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC