2017-07-27 93 views
0

我有未運行下面的查詢使用WITH子句:如何一起選擇與WHERE子句

with countf as (
    select nationid, count(*) as c from customer 
    group by nationid 
), 
maxf as (select max(nationid) from customer) 

select c.customerid, c.nationid from customer c, countf cf, maxf m 
where c.nationid = cf.nationid 
and cf.c = m 

這個問題似乎是m是一個記錄,而不是一個整數。但是,如果我將它作爲子查詢運行如下:

cf.c = (select max(nationid) from customer) 

它按預期工作。我認爲我正在使用with語句而不是預期的方式。試圖

cf.c in maxf 

讓我假設使用WITH只是不應該在一個WHERE子句中使用生成的表。

我知道還有其他方法可以使用all來獲得相同的查詢。我真的只對我應該如何使用with語句感興趣。我以後只能使用它到SELECT嗎?

在此先感謝您提供任何幫助。

+1

另外,您正在使用的連接語法應該是hav e已經死亡。如果您使用顯式連接語法 – JohnHC

+0

@JohnHC指出,那麼您可能會發現這個世界是一個更好的地方,感謝您的支持。我從來沒有真正使用SQL,但我更願意寫在考試紙上,所以我儘量保持簡單:) – lbrndnr

回答

1

這是因爲條件and cf.c = m這應該是像下面

with countf as (
    select nationid, count(*) as c from customer 
    group by nationid 
), 
maxf as (select max(nationid) as max_nationid from customer) 

select c.customerid, c.nationid from customer c, countf cf, maxf m 
where c.nationid = cf.nationid 
and cf.c = m.max_nationid 

旁註:使用適當的ANSI風格JOIN語法是更具可讀性像

select c.customerid, 
c.nationid from customer c 
join countf cf on c.nationid = cf.nationid 
join maxf m on cf.c = m.max_nationid 
+0

真棒,非常感謝你的快速答案!您介意澄清爲什麼使用WITH語句生成的表與內聯子查詢相比需要這麼做? – lbrndnr

0

使用記錄語法:

and row(cf.c) = m 
+0

出於好奇:你能做到嗎?因爲這裏的'm'是一個cte別名? – Rahul

+0

@Rahul是的,我剛剛測試過。 –