2017-07-27 110 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是的,我刚刚测试过。 –