1

One question about Postgresql selects. This works as it should:

SELECT 
  name,SUM(cash)
FROM 
  costumers
GROUP BY (name)

but how can I concat two (or more) fields in the GROUP BY clause? This is what I tried:

SELECT 
  name,SUM(cash)
FROM 
  costumers
GROUP BY (name || ' ' || nickname)
1
  • What is the error message that you got? Commented Aug 21, 2012 at 19:36

1 Answer 1

3

That will work, except that you need to select the expression you group by:

SELECT 
    (name || ' ' || nickname) AS name_and_nickname,
    SUM(cash) AS total_cash
FROM costumers
GROUP BY (name || ' ' || nickname)

Another option is to group by two fields by separating them with a comma:

SELECT 
    name, nickname, SUM(cash) AS total_cash
FROM costumers
GROUP BY name, nickname

Note that these two are not exactly equivalent. In particular these two rows will end up in the same group with the first version and in different groups in the second version:

name    | nickname  | cash
--------+-----------+----
foo     | bar baz   | 10
foo bar | baz       | 20

The second option is probably what you mean.

Sign up to request clarification or add additional context in comments.

2 Comments

wow, thanks a million! this seems to be what i was looking for. I tried both, you wrote these two are not exactly the same. is the difference: the first select, outputs the name and nickname as two coloums. your second example combines the name and nickname coloum to one coloum. if so, this was exactly what i was looking for :)
@tBook: That is also a minor difference, but it's not the one I was referring to. The difference I meant is that the two rows I have shown end up in different groups with the second query, but in the same group with the first query. If there cannot be spaces in the name or nickname then this is not a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.