2017-06-25 6 views
0

私はWITHに新しい列を追加することによって、私のテーブルを変更することを決定したクエリクエリにcountカラムを追加するには?

WITH a as (
SELECT 
     SECTION 
    , MAX(PRICE) over w 
    , MIN(PRICE) over w 
    , AVG(PRICE) over w 
    , TIME t, price 
    , case when MAX(PRICE) over w = price then TIME end maxt 
    , case when MIN(PRICE) over w = price then TIME end mint 
FROM s154 
WINDOW w as (partition by section) 
) 
select DISTINCT 
     SECTION 
    , MAX 
    , MIN 
    , AVG 
    , max(maxt) over (partition by section) 
    , min(mint) over (partition by section) 
from a; 

を持っている:

count(*) FROM s154 GROUP BY section. 

しかし、group by句を追加すると、あまりににより、グループ内の最大値と最小値を求めます。クエリのWITH部分のセクションを数えることは可能ですか?

+0

使用しているデータベースで質問にタグを付けてください。 –

答えて

4

あなただけcount(*) over wを追加することができます。

WITH s as (
     SELECT SECTION, MAX(PRICE) over w as max_price, 
      MIN(PRICE) over w as min_price, AVG(PRICE) over w as avg_price, 
      TIME as t, price, 
      (case when MAX(PRICE) over w = price then TIME end) as maxt 
      (case when MIN(PRICE) over w = price then TIME end) as mint, 
      (COUNT(*) over w) as cnt 
     FROM s154 WINDOW w as (partition by section) 
    ) 
select DISTINCT SECTION, max_price, min_price, avg_price, 
     max(maxt) over (partition by section), 
     min(mint) over (partition by section), 
     cnt 
from s; 

私はこのクエリを簡素化することができる確信しています。いくつか追加して、従う方が簡単です。

  • 明示的な列のエイリアス。自分の列に名前を付けてください。重要です。
  • asの前に列のエイリアスがあるので、名前がどこにあるかわかります。
  • 意味のあるCTE名。この文脈では、「a」は無意味です。少なくとも「s」は表の省略形です。

私は簡単なバージョンがあると思う:

 SELECT SECTION, MAX(PRICE) as max_price, 
      MIN(PRICE) as min_price, AVG(PRICE) as avg_price, 
      (ARRAY_AGG(time ORDER BY price))[1] as time_at_min_price, 
      (ARRAY_AGG(time ORDER BY price DESC))[1] as time_at_max_price 
     FROM s154 
     GROUP BY section; 

これは、ロジックを表現するより良い方法のように思えます。

+0

ありがとう!それは助けになった – Jens

関連する問題