我有两个表JOB和EMP;值是这样的
CREATE TABLE JOB (JOBID SMALLINT UNIQUE NOT NULL,JOBNAME CHAR(15));
CREATE TABLE EMP(EMPID SMALLINT, JOBID SMALLINT, SAL SMALLINT, CITYID SMALLINT);
INSERT INTO JOB(JOBID, JOBNAME) VALUES
( 1, 'DEVELOPMENT'),
(2, 'DEVELOPMENT'),
(3,'TESTING'),
(4,'TESTING'),
(7,'TESTING'),
(9,'RESEARCH'),
(8,'HR');
INSERT INTO EMP (EMPID , JOBID, SAL,CITYID) VALUES
( 100,1,1000,10),
( 200,2,2000,10),
( 300,1,2500,20),
( 400,3,1000,10),
( 500,6,3000,10),
( 600,8,1000,30),
( 700,8,2000,10)
;
我想显示所有工作名称计数和平均工资;作业名称(如果不存在作业ID)则显示0
对于给定的城市ID(Emp表),获取每个作业名称的所有jobid(来自job表),并在Emp表中匹配(如果存在显示计数)(Emp表中存在的jobid的数目),而avssal否则为0,表示count和avgsal 。结果应该按照作业表中作业名称的顺序排列。输出应该是这样
Cityid jobname count avg-sal
10 development 2 1500
10 TESTING 1 1000
10 RESEARCH 0 0
10 HR 1 2000
total 4 1500
20 development 1 2500
20 Testing 0 0
20 Research 0 0
20 HR 0 0
Total 1 2500
Grand Total 5 1700
我尝试通过联接,但是无法正常工作;使用join或Cursor更好吗?
答案 0 :(得分:0)
这是您想要的吗?
select 10 as cityid, jobname, count(e.empid) as cnt,
avg(e.sal)
from jobname j left join
emp e
on e.jobid = j.jobid and e.cityid = 10
group by grouping sets (jobname), () );