我有三张桌子,我想要这个: 对于每项技能,从2016年开始,至少两个训练包的一部分,并以12到17的分数完成,列出技能ID,其类别,级别,作为其一部分的训练包的数量及其平均分数。
我编写了下面的代码,但是当我选择平均值和总和时会出现问题。
select SKILLNUM , SKCATEGORY , SKLEVEL , count(TPID)
from (trainingpack t join Is_part_of i on t.TPID=i.TPID join skill s on i.SKILLNUM=s.SKILLNUM)
where STARTINGDATE like '%2016' and COMPLDATE is not null and score between 12 and 17
and (SKILLNUM) in (
select is_part_of.SKILLNUM
from is_part_of
group by SKILLNUM
having count(TPID) >=2);
我也试过这段代码
select SKILL.SKILLNUM , SKILL.SKCATEGORY , SKILL.SKLEVEL ,count( IS_PART_OF.TPID),sum( IS_PART_OF.SCORE)
from SKILL,TRAININGPACK,IS_PART_OF
where TRAININGPACK.STARTINGDATE like '%2016' and IS_PART_OF.COMPLDATE is not null and IS_PART_OF.score between 12 and 17
and IS_PART_OF.TPID=TRAININGPACK.TPID and IS_PART_OF.SKILLNUM=SKILL.SKILLNUM and (is_part_of.SKILLNUM) in (
select is_part_of.SKILLNUM
from is_part_of
group by SKILLNUM
having count(TPID) >=2);
答案 0 :(得分:0)
只有在SELECT子句中不包含其他列时,才能使用aggregate functions
而不是group by
句子。
例如:您可以在查询中使用下面的select
句子,但您不会像预期的那样通过SKILLNUM,SKCATEGORY和SKLEVEL获得报告。您将只获得全局计数和总和结果:< / p>
select count( IS_PART_OF.TPID),sum( IS_PART_OF.SCORE) from ...
当您查看SKILLNUM,SKCATEGORY和SKLEVEL的报告时,您应在查询结尾处加入group by
条款:
... group by SKILL.SKILLNUM , SKILL.SKCATEGORY , SKILL.SKLEVEL
因此,在不确切知道您的数据库模型的情况下,您的查询应为:
select SKILL.SKILLNUM , SKILL.SKCATEGORY , SKILL.SKLEVEL ,count( IS_PART_OF.TPID),sum( IS_PART_OF.SCORE)
from SKILL, TRAININGPACK, IS_PART_OF
where TRAININGPACK.STARTINGDATE like '%2016'
and IS_PART_OF.COMPLDATE is not null
and IS_PART_OF.score between 12 and 17
and IS_PART_OF.TPID = TRAININGPACK.TPID
and IS_PART_OF.SKILLNUM = SKILL.SKILLNUM
and is_part_of.SKILLNUM in (
select is_part_of.SKILLNUM
from is_part_of
group by SKILLNUM
having count(TPID) >=2)
group by SKILL.SKILLNUM , SKILL.SKCATEGORY , SKILL.SKLEVEL