1

我需要根据起始字母对一列进行分组,然后计算有多少以相应字母开头。这很容易,但我的问题是,如何为列设置名称,这样就不必多次编写相同的内容?

这是我的代码:

SELECT substr(p_nev,1,1) firstLetter, count(substr(p_nev,1,1))
from pizza
group by substr(p_nev,1,1)
order by substr(p_nev,1,1) desc;

请注意,我必须写 substr(p_nev,1,1) 4 次,所以我想用 firstLetter(或一些变量名)以某种方式替换它。

所以这是最优雅的方式吗?

SELECT substr(p_nev,1,1) firstLetter, count(*)
from pizza
group by substr(p_nev,1,1)
order by firstLetter desc;
4

3 回答 3

2

You can wrap query with inner select

select fl, count(*) 
  from (select substr(p_nev,1,1) fl
          from pizza) 
group by fl
order by fl desc;

In my practice optimizer always was subtle enough to make those queries equivalent in terms of execution plan

于 2013-11-02T21:02:42.627 回答
1

您应该能够使用count(*)代替count(substr(p_nev,1,1))order by firstLetter代替order by substr(p_nev,1,1). 但是,您将不得不拼出该group by子句,因为选择列表中的别名发生在查询分组之后。

于 2013-11-02T20:55:41.053 回答
1

作为替代方案,您还可以使用公用表表达式:

with letters as (
   SELECT substr(p_nev,1,1) as firstLetter
   from pizza
)
select firstletter, count(*) as cnt
from letters
group by firstletter
order by firstletter desc;

公用表表达式(以 开头的部分with letters ..)的作用类似于派生表(“动态视图”),如果您在更大的查询中多次需要它,则特别方便。

性能方面,alko 的回答没有区别。

于 2013-11-02T21:06:36.987 回答