简体   繁体   中英

sql group by column name

I though that GROUP BY must follow by column, but on internet found such example, and don't how and why it works? I am using ORACLE

Working:

SELECT TRUNC(SALARY/5000 , 0), COUNT(*)
FROM EMPLOYEES
GROUP BY TRUNC(SALARY/5000 , 0);

Not working:

SELECT SALARY, COUNT(*)
FROM EMPLOYEES
GROUP BY TRUNC(SALARY/5000 , 0);

Who told you that you can group by columns only? This is just not true.

You group by expressions. These can be columns (eg salary ) or any other operations on the selected row like salary * tax , salary * 100 , etc.

GROUP BY x, y means you want to aggregate your data to get one result row per x/y pair.

If you group by TRUNC(SALARY/5000, 0) you get one result row per expression result. The salaries 5100, 5200, and 9000 will be in one group, because their result is 1, the salaries 11000 and 13000 will be in another.

COUNT(*) gives you the number of salaries in that group, but you cannot select SALARY , because there is not one salary in the group you could show, there can be many. If you want to show a salary, decide which one. The minimum MIN(salary )? The maximum MAX(salary )? The average AVG(salary )?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM