SQL:如何重用count(*)计算值?

时间:2015-01-21 14:29:29

标签: sql postgresql

我使用的是Postgres 9.4。

我的查询中有一个select语句,如下所示:

SELECT date_part('year'::text, c.date) AS yyyy,
    to_char(c.date, 'MM'::text) AS monthnumber,
    to_char(c.date, 'TMMonth'::text) AS monthname,
    l.id AS lineID,
    n.id AS networkID,
    l.name AS lineName,
    count(c.*) AS count,
    count(distinct(c.date)) AS number_of_journeys,

我想重用最后两列(计算出的列)来计算另一列,如下所示:

SELECT date_part('year'::text, c.date) AS yyyy,
    to_char(c.date, 'MM'::text) AS monthnumber,
    to_char(c.date, 'TMMonth'::text) AS monthname,
    l.id AS lineID,
    n.id AS networkID,
    l.name AS lineName,
    count(c.*) AS count,
    count(distinct(c.date)) AS number_of_journeys,
    count / number_of_journeys AS frequentation_moyenne

是否可以这样做?

谢谢

1 个答案:

答案 0 :(得分:1)

不在SQL Server中,您必须使用以下方法之一:

SELECT date_part('year'::text, c.date) AS yyyy,
to_char(c.date, 'MM'::text) AS monthnumber,
to_char(c.date, 'TMMonth'::text) AS monthname,
l.id AS lineID,
n.id AS networkID,
l.name AS lineName,
count(c.*) AS count,
count(distinct(c.date)) AS number_of_journeys,
count(c.*) / count(distinct(c.date)) AS frequentation_moyenne

OR

Select yyyy, monthnumber, monthname, lineID, networkID, lineName, count, number_of_journery, count / number_of_journeys AS frequentation_moyenne
from
(SELECT date_part('year'::text, c.date) AS yyyy,
to_char(c.date, 'MM'::text) AS monthnumber,
to_char(c.date, 'TMMonth'::text) AS monthname,
l.id AS lineID,
n.id AS networkID,
l.name AS lineName,
count(c.*) AS count,
count(distinct(c.date)) AS number_of_journeys)