1

我怎么能做这样的事情

select 
    a.atest, a.btest, a.ctest, b.atest, b.btest
from 
    test.dbo.rm a(nolock)
cross apply 
    wat.dbo.ar(a.atest,a.btest) b
where 
    a.rmd = 9 and a.btest > 0

alter function ar(@atest varchar(25), @btest numeric(19,5)) 
returns table as 
    return
    (
        select atest, btest from test.dbo.rm (nolock)
        where rmd = 1 and atest=@atest and btest=@btest
    )

使用删除语句或更新。我不想重复,所以在我选择一个之后,b.atest我想删除记录b.atest或设置b.btest为 0。这个查询正在处理包含大约 5-10 百万条记录的表。所以它必须很快。

4

1 回答 1

1

使用不带功能的查询:

select a.atest,a.btest,a.ctest,b.atest,b.btest
from test.dbo.rm a(nolock)
cross apply (
        select top 1 atest, btest 
        from test.dbo.rm t (nolock)
        where t.rmd = 1 and t.atest=a.atest and t.btest=a.btest
        )b
where a.rmd = 9 and a.btest > 0

您还可以使用左连接而不是交叉应用:

select *
from (
    select a.atest,a.btest,a.ctest,b.atest,b.btest,
          row_number() over ( partition by b.atest, b.btest order by b.id) as row
    from test.dbo.rm a(nolock)
    LEFT JOIN test.dbo.rm b ON b.rmd = 1 and b.atest=a.atest and b.btest=a.btest
    where a.rmd = 9 and a.btest > 0
)z
where z.row = 1
于 2014-07-28T10:15:15.120 回答