×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

向SQL.高手请教,怎样用T-SQL写这个store procedure,实现需求。谢谢。

A table has 2 columns:

ColA int
ColB datetime

Input some data as
ColA ColB
1 2/2/2005 (month/day/year)
1 2/3/2005
1 2/10/2005
1 3/10/2005
2 3/1/2005
2 3/5/2005
2 4/1/2005
2 5/1/2005

Need to write a store procedure:
The procedure has an input argument
refTime as datatime

What it do is:
For each group of rows with the same ColA, remove the rows which ColB < refTime, except the one which is the nearest to the refTime.

For example,
if refTime==2/5/2005, the following rows will be removed:
ColA ColB
1 2/2/2005

if refTime==3/6/2005, the following rows will be removed:
ColA ColB
1 2/2/2005
1 2/3/2005
2 3/1/2005
Report

Replies, comments and Discussions:

  • 工作学习 / 专业技术讨论 / 向SQL.高手请教,怎样用T-SQL写这个store procedure,实现需求。谢谢。
    A table has 2 columns:

    ColA int
    ColB datetime

    Input some data as
    ColA ColB
    1 2/2/2005 (month/day/year)
    1 2/3/2005
    1 2/10/2005
    1 3/10/2005
    2 3/1/2005
    2 3/5/2005
    2 4/1/2005
    2 5/1/2005

    Need to write a store procedure:
    The procedure has an input argument
    refTime as datatime

    What it do is:
    For each group of rows with the same ColA, remove the rows which ColB < refTime, except the one which is the nearest to the refTime.

    For example,
    if refTime==2/5/2005, the following rows will be removed:
    ColA ColB
    1 2/2/2005

    if refTime==3/6/2005, the following rows will be removed:
    ColA ColB
    1 2/2/2005
    1 2/3/2005
    2 3/1/2005
    • "select top1 ColA, Max(ColB) from table1 where ColB<= refTime group by ColA order by ColA desc." 没太看懂两个Remove是要干吗用的 ? delete ?
      • 谢谢。Remove 就是delete 掉那些符合条件的 rows。
    • oh ...俺没看清楚需求。select 语句应该这么写: Select t1.ColA,t2.ColB from Table1 t1,(select max(ColB) as ColB from table1 where ColB<=refTime) t2 where t1.ColB=t2.ColB.
      • 那就是delete from Table1 where ColB <= (select max(ColB) from table1 where ColB <=refTime)
        • delete from Table1 where COlB < (select max(ColB) from table1 where ColB <=refTime) (没等于,sorry )
          • 谢谢热心。select 语句还没看懂,不过上面的delete 语句不对。要求是:For each group of rows with the same ColA ('1' or '2' or ... ), remove the rows which ColB<refTime,
            except the one which is the nearest to the refTime.

            For example,
            if refTime==3/6/2005, the following rows will be removed:
            ColA ColB
            1 2/2/2005
            1 2/3/2005
            2 3/1/2005


            而这两个rows 不要被删掉:
            ColA ColB
            1 2/10/2005
            2 3/5/2005
            • 哦,这样啊,还有each group的要求,俺从小就审题不仔细,不好意思啊。 那就是delete table1 t1 from( select ColA, Max(ColB) from table1 where ColB<= refTime group by ColA ) t2 where t1.ColA=t2.ColA and t1.ColB < t2.ColB