在DB2中,我试图在GROUP BY中获取不同的字段,同时也在每行中获取特定值的平均值。
我认为问题在于我正在尝试在AVG子句中使用CASE
所以它说'AS'不应作为令牌,我认为它在AVG中我的第一个CASE中。
所以:
SELECT
number,
customer,
group,
groupDetail,
category,
detail,
detailName,
avg(countOfSales),
avg(annuals),
avg(case when trajectory is null then 0 else trajectory end as trajectory),
avg(annualsLocation),
avg(case when trajLocation is null then 0 else trajLocation end as trajLocation),
avg(annualsWhole),
avg(case when trajWhole is null then 0 else trajWhole end as trajWhole)
FROM salesReporting
WHERE customer = 123
group by number,customer,group,groupDetail,category,detail,detailName
ORDER BY customer,groupDetail,category,detail ASC
我想要
customer | group | groupDetail | category | detail | detailName | countOfSales | annuals | trajectory | annualsLocation | trajLocation | annualsWhole | trajWhole
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
123 1 Atl. Sls New NewLoc 12345 2948 124.84 8372 246.08 8372 28.84
123 1 Atl. Sls New NewLoc 12345 2345 164.84 4839 234.08 4839 26.63
123 1 Atl. Sls New NewLoc 12345 6523 224.84 2345 654.08 2345 29.85
123 1 Atl. Sls New NewLoc 12345 3456 134.84 5434 152.08 5434 25.34
123 1 Atl. Sls New NewLoc 12345 3426 124.84 6234 245.08 6234 28.84
如何在DB2中正确实现?
答案 0 :(得分:1)
这是一个语法问题,别名“轨迹应在avg括号之外
例如:
avg(case when trajectory is null then 0 else trajectory end) as trajectory
答案 1 :(得分:0)
使用coalesce()
可以更简单地编写此逻辑:
avg(coalesce(trajectory, 0)) as trajectory,
. . .