1

如果您有下面的选择语句,其中 PK 是主键:

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

并且输出是这样的(为了清楚起见,第一个数字是间隔的):

      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

你想输出这样的东西:

      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

是不是可以让PK中的“00”在单选内有“身份”的数字效果?否则,您如何为该日期的每个找到的活动将数字加 1?

我在输入时已经在考虑尝试用 group by 尝试 Sum(case when ?? then 1 end) 之类的东西。

编辑:(下面由 JohnFX 提供的答案)

这是最终的答案:

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
4

2 回答 2

3

我认为您正在寻找ROW_NUMBER和相关的 PARTITION 子句。

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

如果 DateEntered 有重复的值,您可能还需要检查DENSE_RANK()RANK(),具体取决于您在这些情况下如何处理增量器的具体需求。

于 2010-05-19T15:20:22.583 回答
2

日期时间列永远不应用作主键。另外,如果你有一个 indetity 列,你不能有:

      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 

As2010 01 01 01将具有与 相同的身份2010 02 14 01

最好的方法是分开一个标识列,将您的假期日期放在另一列中,并将转换后nvarchar的每个字段的值连接起来。

于 2010-05-19T15:30:12.747 回答