1

I have a table with data as company name, employee name, leave days. I want to extract the company name and min date for an employee. For this I am using this query

select companyname, min(date) from table where companyname = 'apple' and employeename = 'ABC'

This query however fails saying that column "tablename.companyname" must appear in the GROUP BY clause or be used in an aggregate function.

I did try using companyname in group by clause along with date but this gave me a lot of values instead of one minimum date.

Can any one figure out how to do this without adding to complexities.

I did figure out the solution. However, I didn't quite understand why it asked me to use companyname in the group by clause.

4
  • What was the query you used with the group by? Posting that will help people troubleshoot your issue. Commented Jun 17, 2014 at 19:25
  • 1
    You wanted a minimum date for a Companyname so you would want the data grouped by the Companyname and then fetch the minimum in the list. hence the Group by CompanyName :). The compiler does not care that your where clause restricts it to one CompanyName. As far as it is concerned if you have an aggregate function on a column and a column with no aggregate function. you need to tell it what to do with the column you did not put the aggregate function on. Commented Jun 17, 2014 at 19:26
  • @TMNT2014 : Okay. Understood. Is this exhibited only by postgres or other DBMS also? Commented Jun 17, 2014 at 21:49
  • As far as I know TSQL and Oracle behave the same way. Commented Jun 18, 2014 at 2:23

1 Answer 1

4

It is standard SQL requirement that you GROUP BY columns that are not aggregated.

SELECT companyname, min(date) AS min_date
FROM   tbl
WHERE  companyname = 'apple'
AND    employeename = 'ABC'
GROUP  BY companyname;

You can use a positional reference to shorten the code in Postgres:

...
GROUP  BY 1;

Or drop the pre-determined column companyname from the SELECT list. Then you don't need GROUP BY either:

SELECT min(date) AS min_date
FROM   tbl
WHERE  companyname = 'apple'
AND    employeename = 'ABC';
Sign up to request clarification or add additional context in comments.

1 Comment

Or maybe they want SELECT companyname, min(date) AS min_date … GROUP BY companyname ORDER BY min_date LIMIT 1;. Of course, in that case no grouping is needed

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.