简体   繁体   English

SQL AVG函数

[英]SQL AVG function

What is the correct syntax to display the data from all records using GROUP (or DISTINCT) and AVG? 使用GROUP(或DISTINCT)和AVG显示来自所有记录的数据的正确语法是什么?

My data looks like this: TABLE NAME: Pensje COLUMNS: ID, Company, Position, Salary 我的数据如下所示:表名称:Pensje栏目:ID,公司,职位,薪水

Example:
ID    Company   Position   Salary
1      Atari      Designer   24000
2      Atari      Designer   20000
3      Atari      Programmer 35000
4      Amiga      Director   40000

I need to arrange data in this way (only records from 1 company need to be displayed) 我需要以这种方式排列数据 (仅需要显示1家公司的记录)

Position a , average Salary from all the records with same Company and Position
Position b , average Salary from all the records with same Company and Position

Ex. Atari

Designer, 22000
Programmer, 35000

My SQL looks like this: 我的SQL看起来像这样:

SELECT Position, AVG(Salary)
FROM Pensje
WHERE Company = %s
GROUP BY Position
ORDER BY Position ASC

In the above example "Position" is displayed correctly, "Salary" is not displayed at all, while after removing AVG() is displayed but only first position found in table 在上面的示例中,“位置”正确显示,而“薪水”则完全不显示,而在删除AVG()之后,仅显示了表中的第一个位置

Many thanks for taking your time to help me! 非常感谢您抽出宝贵的时间来帮助我!

Posting an answer from MCP_infiltrator which helped: 从MCP_infiltrator发布答案有助于:

In your WHERE clause you should be using WHERE Company LIKE '%s' not = The way you have it written, should produce the results you want so I do not understand why it is not working properly for you. 在您的WHERE子句中,您应该使用WHERE Company LIKE'%s'not =您编写的方式应该产生想要的结果,所以我不明白为什么它不能正常工作。 You may also want to alias your AVG() results like AVG(Salary) AS Average_Salary otherwise your column will comback with no name. 您可能还想给AVG()结果加上别名,例如AVG(Salary)AS Average_Salary,否则您的列将不显示名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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