Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

sql - Accessing column alias in postgresql

Having a little bit of trouble understanding how a query alias works in postgresql. I have the following:

SELECT DISTINCT robber.robberid,
                nickname,
                Count(accomplices.robberid) AS count1
FROM   robber
       INNER JOIN accomplices
               ON accomplices.robberid = robber.robberid
GROUP  BY robber.robberid,
          robber.nickname
ORDER  BY Count(accomplices.robberid) DESC;


 robberid |            nickname            | count1 
----------+--------------------------------+--------
       14 | Boo Boo Hoff                   |      7
       15 | King Solomon                   |      7
       16 | Bugsy Siegel                   |      7
       23 | Sonny Genovese                 |      6
        1 | Al Capone                      |      5
 ...

I can rename the "count1" column using the as command but I can't seem to be able to refer to this again in the query? I am trying to include a HAVING command at the end of this query to query only objects who have a count less than half of the max.

This is homework but I am not asking for the answer only a pointer to how I can include the count1 column in another clause.

Can anyone help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general, you can't refer to an aggregate column's alias later in the query, and you have to repeat the aggregate

If you really want to use its name, you could wrap your query as a subquery

SELECT * 
FROM
(
    SELECT DISTINCT robber.robberid, nickname, count(accomplices.robberid)  
    AS count1 FROM robber                   
    INNER JOIN accomplices  
    ON accomplices.robberid = robber.robberid  
    GROUP BY robber.robberid, robber.nickname  
) v
ORDER BY count1 desc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...