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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SQL Query help, DISTINCT

Author  Topic 

JeffS23
Posting Yak Master

212 Posts

Posted - 2008-01-04 : 13:19:31
I'm working to obtain distinct records from a table. The query I have so far works great.

SELECT DISTINCT Story.Title
FROM Story INNER JOIN
StoryTag ON Story.StoryID = StoryTag.storyID
WHERE (StoryTag.tagID = '73') AND (Story.deleted = 'N')
ORDER BY Story.Title


---- The issue I'm having is that I need more than just the Story.Title, I need two other fields IngestDate, storyID. however, when I add those fields, the query no longer returns distinct titles.

SELECT DISTINCT Story.Title, Story.storyid, Story.IngestDate
FROM Story INNER JOIN
StoryTag ON Story.StoryID = StoryTag.storyID
WHERE (StoryTag.tagID = '73') AND (Story.deleted = 'N')
ORDER BY Story.Title

Any ideas on how I can get distinct records based on the title with the remaining fields?

Thanks

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-01-04 : 13:38:54
Use a derived table as shown in an answer for you yesterday:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=94978


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2008-01-04 : 13:42:20
That's because if a Title has more than storyid or ingestdate, you will get more than 1 record for each title. Is there a way to make the storyid or ingestdate unique? Like

SELECT story.title,[Storyid] = max(story.storyid), [IngestDate] = max(story.ingestDate)
FROM Story INNER JOIN
StoryTag ON Story.StoryID = StoryTag.storyID
WHERE (StoryTag.tagID = '73') AND (Story.deleted = 'N')
GROUP BY story.Title
ORDER BY story.Title
Go to Top of Page
   

- Advertisement -