2016-07-24 1 views
1

ネットで検索されていて、CTEのないウィンドウ関数を含むクエリを作成しようとしましたが、結果を得ることができず、いくつかの助けが必要です 私は私がやっている必要なものCTEを作成し、1つのクエリでCTEなしで1つのクエリでウィンドウ関数を適用する

;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 
+0

CTEを使用する際の問題点は何ですか?なぜCTEを避けようとしていますか? –

答えて

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) 

これは以下のように動作します。..

01以下は
T-SQL Querying (Developer Reference)

いくつかのサンプルです:並べによって

1.order絆オプションで自分のランク
2.Top 1に基づいて、すべての行が

参考に関連付けられているすべての行をフェッチ再生するデータ:

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) 
0

CTEはサブクエーに直接変換できますy。あなたのクエリは次のようになります。

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があります(よくあるエラーです)。

関連する問題