簡體   English   中英

在 SQL 紅移中加入 WITH 表

[英]Join WITH tables in SQL redshift

with temp as(
select  account_id, asm_signatures_classification, count(*) 
from asm_insights 
where date = '2020-05-20'
group by account_id, asm_signatures_classification
order by account_id
)

with temp2 as(
select  account_id, app_id
from asm_insights 
where date = '2020-05-20'
)

select * from temp join temp2 on temp.account_id = temp2.account_id`enter code here`

我想用較小的表來做一些練習,我怎樣才能像這樣加入 2 個臨時表? 我做了什么得到一個錯誤:SQL 錯誤 [500310] [42601]:亞馬遜無效操作:“with”處或附近的語法錯誤 Position:195;

不要重復with with定義多個 CTE:

with temp as (
      select  account_id, asm_signatures_classification, count(*) as cnt
      from asm_insights 
      where date = '2020-05-20'
      group by account_id, asm_signatures_classification
     ),
     temp2 as (
      select account_id, app_id
      from asm_insights 
      where date = '2020-05-20'
     )
select *
from temp join
     temp2
     on temp.account_id = temp2.account_id;

當然,這似乎是一個愚蠢的例子,因為這不需要 CTE。 盡管如此,我還是解決了一些問題:

  • ORDER BY在 CTE 中不合適(除非您限制行數)。
  • 所有列都應該有別名。

這個特別的查詢更簡單地寫成:

select account_id, app_id, asm_signatures_classification
       cont(*) over (partition by account_id, asm_signatures_classification)
from asm_insights 

其中日期 = '2020-05-20'

請使用以下查詢,

with temp as (
select  account_id, asm_signatures_classification, count(*) 
from asm_insights t1
inner join (select  account_id, app_id from asm_insights where date = '2020-05-20') t2
on (temp.account_id = temp2.account_id)
where date = '2020-05-20'
group by account_id, asm_signatures_classification
order by account_id)
select * from temp;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM