我正在使用Oracle SQL,我需要查询帮助。
我有下表:
Age (int)
Salary (int)
输入例如:
Age | Slary
18 | 5000
18 | 10000
20 | 11000
24 | 9000
21 | 6000
21 | 7000
22 | 6000
28 | 22000
我需要按年龄范围计算平均工资。每两年都是风靡一时。输出例如:
Age Range | Average Salary
18 - 20 | 8666.666
19 - 21 | 8000
20 - 22 | 7500
21 - 23 | 6333.33
22 - 24 | 7500
23 - 25 | 7500
24 - 26 | 7500
26 - 28 | 22000
27 - 29 | 22000
28 - 30 | 22000
顺便说一下,如果它更容易实现,可以将“年龄范围”列分为两个不同的列:“最小年龄”和“最大年龄”。
任何建议如何做到这一点?
答案 0 :(得分:1)
这可能会有所帮助(MSSQL脚本):
SELECT Cast(LowerLimit AS VARCHAR) + ' - '
+ Cast(UpperLimit AS VARCHAR) AgeRange,
Avg(salary) averagesalary
FROM MyTable t1
RIGHT OUTER JOIN (SELECT Age AS LowerLimit,
Age + 2 AS UpperLimit
FROM MyTable) AS t2
ON t1.Age >= t2.LowerLimit
AND t1.Age <= t2.UpperLimit
GROUP BY LowerLimit,UpperLimit
答案 1 :(得分:0)
我认为这可能是你想要的(它部分改编自Deepak Pawar的答案,但调整为Oracle语法)。我注意到23-25
组的值在我的查询中是9000,而在样本数据中是7500,但我认为样本数据不正确且9000确实是正确的值(也适用于24-26
) 。
Oracle不是我选择的数据库,我确信更熟悉Oracle开发的人可以改进查询。
Oracle 11g R2架构设置:
CREATE TABLE t ("Age" int, "Salary" int);
INSERT ALL
INTO t ("Age", "Salary") VALUES (18, 5000)
INTO t ("Age", "Salary") VALUES (18, 10000)
INTO t ("Age", "Salary") VALUES (20, 11000)
INTO t ("Age", "Salary") VALUES (24, 9000)
INTO t ("Age", "Salary") VALUES (21, 6000)
INTO t ("Age", "Salary") VALUES (21, 7000)
INTO t ("Age", "Salary") VALUES (22, 6000)
INTO t ("Age", "Salary") VALUES (28, 22000)
SELECT * FROM dual;
查询1 :
WITH counter
AS (
SELECT
LEVEL-1 low,
LEVEL+1 high
FROM DUAL
WHERE (LEVEL-1) >= (SELECT MIN("Age") FROM t)
CONNECT BY LEVEL-1 <= (SELECT MAX("Age") FROM t)
)
SELECT
(low || ' - ' || high) "Age Range",
Avg("Salary") "Average Salary"
FROM t
RIGHT OUTER JOIN counter c ON t."Age" >= c.low AND t."Age" <= c.high
GROUP BY low, high
ORDER BY 1
<强> Results 强>:
| AGE RANGE | AVERAGE SALARY |
|-----------|-------------------|
| 18 - 20 | 8666.666666666666 |
| 19 - 21 | 8000 |
| 20 - 22 | 7500 |
| 21 - 23 | 6333.333333333333 |
| 22 - 24 | 7500 |
| 23 - 25 | 9000 |
| 24 - 26 | 9000 |
| 25 - 27 | (null) |
| 26 - 28 | 22000 |
| 27 - 29 | 22000 |
| 28 - 30 | 22000 |