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 2008 Forums
 Transact-SQL (2008)
 Unique count

Author  Topic 

JMOE
Starting Member

4 Posts

Posted - 2011-06-27 : 17:07:37
Hello all,

Looking for the correct way to add a unique or first instance column for my query.

would like to be able to add a frist count as 1 on the frist instance and then 0 for every instance after that.

Before
Type STATE DATE
APPLE AZ 6/25/2011
APPLE AZ 6/26/2011
APPLE CA 6/27/2011
GRAPE AZ 6/28/2011
GRAPE AZ 6/25/2011
NUT CA 6/26/2011
NUT CA 6/27/2011
NUT NM 6/28/2011

after

Type STATE DATE Frist instance
APPLE AZ 6/25/2011 1
APPLE AZ 6/26/2011 0
APPLE CA 6/27/2011 0
GRAPE AZ 6/28/2011 1
GRAPE AZ 6/25/2011 0
NUT CA 6/26/2011 1
NUT CA 6/27/2011 0
NUT NM 6/28/2011 0

Thanks Joe

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-06-27 : 17:34:58
;WITH cteSource AS (SELECT Type, State, Date, ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Date) AS SeqID FROM Table1)
SELECT Type, State, Date, CASE WHEN SeqID = 1 THEN 1 ELSE 0 END AS [First instance] FROM cteSource



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -