2016-12-24 196 views
-3

我有三個表,我想要這個: 對於每個技能,開始於2016年,並且是至少兩個培訓包的一部分,並且分數介於12和17之間,列出技能ID,其類別,其水平,作爲其一部分的訓練包數量及其平均得分。SQL中的聚合函數

我寫了下面的代碼,但當我選擇avg和sum時出現問題。

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

顯示示例表 – DCR

+0

首先找出您正在使用的RDBMS。然後參見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

+0

您可能需要在group by子句中添加其他列。所以GROUP BY SkillNum,SkCategory,SkLevel –

回答

0

您可以使用aggregate functions沒有group by一句話,只要你不包括你的SELECT子句中其他列。

例如:可以使用下面的句子select在您的查詢,但你希望你不會得到通過SKILLNUM,SKCATEGORY和SKLEVEL報告..你將只能得到全球數和金額的結果:

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