开发者

SQL: without a cursor, how to select records making a unique integer id (identity like) for dups?

If you have the select statement below where the PK is the primary key:

select  distinct dbo.DateAsInt( dateEntered) * 100 as PK, 
                 recordDescription as Data
from    MyTable

and the output is something like this (the first numbers are spaced for clarity):

      PK             Data
2010 01 01 00    New Years Day
2010 01 01 00    Make Resolutions
2010 01 01 00    Return Gifts
2010 02 14 00    Valentines day
2010 02 14 00    Buy flowers

and you want to output something like this:

      PK             Data
2010 01 01 01    New Years Day
2010 01 01 02    Make Resolutions
2010 01 01 03    Return Gifts
2010 02 14 01    Valen开发者_如何学Gotines day
2010 02 14 02    Buy flowers

Is it possible to make the "00" in the PK have an "identity" number effect within a single select? Otherwise, how could you increment the number by 1 for each found activity for that date?

I am already thinking as I type to try something like Sum(case when ?? then 1 end) with a group by.

Edit: (Answer provided by JohnFX below)

This was the final answer:

select    PK + row_number() over 
          (PARTITION BY eventid order by eventname) as PK,
          recordDescription
from      (select   distinct  -- Removes row counts of excluded rows)
                    dbo.DateAsInt( dateEntered) as PK,
                    recordDescription as Data
           from     MyTable) A
order by eventid, recordDescription


I think you are looking for ROW_NUMBER and the associated PARTITION clause.

SELECT DISTINCT dbo.DateAsInt(DateEntered) * 100 as PK, 
                 ROW_NUMBER() OVER (PARTITION BY DateEntered ORDER BY recordDescription) as rowID,
                 recordDescription as Data
FROM MyTable

If DateEntered has duplicate values you probably also want to check out DENSE_RANK() and RANK() depending on your specific needs for what to do with the incrementor in those cases.


Datetime columns should never ever be used as primary key. Plus, if you had an indetity column, you couldn't have:

      PK             Data 
2010 01 01 01    New Years Day 
2010 01 01 02    Make Resolutions 
2010 01 01 03    Return Gifts 
2010 02 14 01    Valentines day 
2010 02 14 02    Buy flowers 

As 2010 01 01 01 would have the same identity as 2010 02 14 01.

The best approach would be to have an identity column apart, and have your holiday date in another column, and concatenate the converted to nvarchar value of each of these fields.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜