在没有CTE的一个查询中应用窗口函数

时间:2016-07-24 09:51:49

标签: sql-server tsql sql-server-2008-r2

我在网上搜索并试图创建一个包含没有CTE的窗口函数的查询但是我无法得到结果而我需要一些帮助 这是我用CTE创建的查询,我需要的是在一个查询中执行此操作

;with cte(Gid, id, prod, orderdate, shipdate, ranking) as
(
    select 
        p1.Gid  Gid,
        p1.id id,
        p1.prod prod,
        p1.orderdate orderdate,
        p2.shipdate shipdate,
        rank() over (partition by p1.prod order by p1.id desc) ranking
    from 
        shpro p1 
    inner join 
        shpro p2 on p1.id = p2.id
    where 
        cast(p1.orderdate as DATE) > GETDATE() 
        and cast(p1.shipdate as DATE) < GETDATE() - 1
)
select * 
from cte 
where ranking = 1

2 个答案:

答案 0 :(得分:0)

Demo with some test data on how this works

 select top (1) with ties
                p1.Gid  Gid,
                p1.id id,
                p1.prod prod,
                p1.orderdate orderdate,
                p2.shipdate shipdate       
          from shpro p1 inner join shpro p2
          on p1.id=p2.id
          where cast(p1.orderdate as DATE)>GETDATE() and cast(p1.shipdate as DATE)<GETDATE()-1
          order by
          Rank() over (partition by p1.prod order by p1.id desc) 

这就像下面这样......

1. order by根据他们的等级排列所有行 2.Top 1 with ties选项获取所有绑定的行

<强>参考文献:
T-SQL Querying (Developer Reference)

以下是一些可以使用的示例数据:

  CREATE TABLE #TEST
    (
    Id INT,
    Name VARCHAR(10)
    )

    Insert Into #Test
    select 1,'A'
    Union All
    Select 1,'B'
    union all
    Select 1,'C'
    union all
    Select 2,'D'



select top 1 with ties id,name
from #test
order by row_number() over (partition by id order by id)

答案 1 :(得分:0)

CTE可以直接翻译成子查询。您的查询应类似于以下内容:

SELECT * FROM
(
    select 
        p1.Gid  Gid,
        p1.id id,
        p1.prod prod,
        p1.orderdate orderdate,
        p2.shipdate shipdate,
        rank() over (partition by p1.prod order by p1.id desc) ranking
    from 
        shpro p1 
    inner join 
        shpro p2 on p1.id = p2.id
    where 
        cast(p1.orderdate as DATE) > GETDATE() 
        and cast(p1.shipdate as DATE) < GETDATE() - 1
) CteAsSubquery
WHERE ranking = 1

注意别名CteAsSubquery(最常见的错误)。