所以我对SQL很陌生,到目前为止几乎完全是自学成才。我目前正在尝试对员工队伍进行一些分析,我试图将15个以上的级别“重新分类”到4个级别。然后我想根据这些类别进行分组,但遇到了一些麻烦(SQL for Dummies似乎已经失去了动力,或者我找不到答案......)。
无论如何,我现在的查询如下。这给出了一个错误,即group by必须包含一个不是外部引用的列,我理解,但不知道如何解决。
编辑:我的目标是获得一个给我以下结果的结果:RANK Hours etc
Equity Partner 12
Fixed Share Partner 20
Associate 50
Trainee 25
Other 15
非常感谢任何帮助 马特
declare @startperiod as integer
declare @endperiod as integer
declare @offc as integer
declare @dept as varchar(3)
select @startperiod = '201101'
select @endperiod = '201112'
select @offc = '55'
select
case k.rank_code
when '10' then 'Equity Partner'
when '110' then 'Fixed Share Partner'
when '130' then 'Associate'
when '131' then 'Associate'
When '132' then 'Associate'
when '133' then 'Associate'
when '134' then 'Associate'
when '135' then 'Associate'
when '136' then 'Associate'
when '137' then 'Associate'
when '141' then 'Associate'
when '142' then 'Associate'
when '341' then 'Trainee'
when '342' then 'Trainee'
else 'Other'
end as 'Rank Desc',
sum(b.base_hrs) as 'Base Hrs',sum(b.tobill_hrs) as 'ToBill Hrs',sum(b.billed_hrs) as 'Billed Hrs',
sum(b.base_amt) as 'Base Amt',sum(b.tobill_amt) as 'ToBill Amt',sum(b.billed_amt) as 'Billed Amt'
from blh_billed_fees b, tbl_rank k, tbm_persnl p
where b.tk_empl_uno = p.empl_uno
and p.rank_code = k.rank_code
group by 'Rank Desc'
答案 0 :(得分:2)
您无法使用当前选项中定义的列进行分组。
选择一个子查询,然后您可以使用RankDesc列来制作组。
最终查询应该是这样的:
select
aux.RankDesc as 'Rank Desc',
sum(aux.base_hrs) as 'Base Hrs',
sum(aux.tobill_hrs) as 'ToBill Hrs',
sum(aux.billed_hrs) as 'Billed Hrs',
sum(aux.base_amt) as 'Base Amt',
sum(aux.tobill_amt) as 'ToBill Amt',
sum(aux.billed_amt) as 'Billed Amt'
from
(select
case k.rank_code
when '10' then 'Equity Partner'
when '110' then 'Fixed Share Partner'
when '130' then 'Associate'
when '131' then 'Associate'
When '132' then 'Associate'
when '133' then 'Associate'
when '134' then 'Associate'
when '135' then 'Associate'
when '136' then 'Associate'
when '137' then 'Associate'
when '141' then 'Associate'
when '142' then 'Associate'
when '341' then 'Trainee'
when '342' then 'Trainee'
else 'Other'
end as 'RankDesc',
b.base_hrs,
b.tobill_hrs,
b.billed_hrs,
b.base_amt,
b.tobill_amt,
b.billed_amt
from blh_billed_fees b, tbl_rank k, tbm_persnl p
where b.tk_empl_uno = p.empl_uno
and p.rank_code = k.rank_code) aux
group by aux.RankDesc
答案 1 :(得分:0)
要么使它成为子查询,要么按其结果字段进行分组,或者(如果它可以重复使用,可以说更好)通过其字段创建视图和组。
答案 2 :(得分:0)
select with case必须是一个子查询,这使得它在paarent执行时显示为一个表,然后可以轻松地对其应用分组。