Sql 创建具有不同位置的行

Sql 创建具有不同位置的行,sql,sql-server,count,pivot,average,Sql,Sql Server,Count,Pivot,Average,我有这个代码来获取列表中所有项目的用户数量和平均级别 select itemId,count(c.characterid) as numberOfUse, avg(maxUpgrade) as averageLevel from items i inner join characters c on i.characterId=c.characterId where itemid in (22001,22002,22003,22004,22005,22006,22007,22008,22009

我有这个代码来获取列表中所有项目的用户数量和平均级别

select  itemId,count(c.characterid) as numberOfUse, avg(maxUpgrade) as averageLevel
from items i inner join characters c on i.characterId=c.characterId 
where itemid in (22001,22002,22003,22004,22005,22006,22007,22008,22009,22010,22011,22012,22013,22014,22015,22016,22030,22031,22032,22033,22034,22035,22036,22037,22038,22039,22040,22041,22042,22050,22051,22052,22053,22054,22055,22056,22057,22058,22059,22060,22070,22071,22072,22073,22074,22075,22076,22077,22085,22086,22087,22091,22092) 
and attached>0
group by itemId
它会为符文id创建一行,一行表示用户数量,一行表示升级符文的普通级别人员,它会为服务器的所有玩家创建一行


我想创建一个新的列每10个级别有统计每10个级别,所以我可以看到什么项目是更多地使用取决于球员的水平。项目级别取决于级别,因此我只选择某个级别的方法是使用
WHERE itemid>0和itemid如果我正确地遵循这一点,您可以进行条件聚合。假设“级别”存储在表
字符
中的
级别
列中,您将执行以下操作:

select i.itemId,
    sum(case when c.level between  1 and 10 then 1 else 0 end) as use_1_10,
    avg(case when c.level between  1 and 10 then maxUpgrade end) as avg_level_1_10,
    sum(case when c.level between 11 and 20 then 1 else 0 end) as use_11_20,
    avg(case when c.level between 11 and 20 then maxUpgrade end) as avg_level_11_20,
    ...
from items i 
inner join characters c on i.characterId = c.characterId 
where i.itemid in (...)  and attached > 0
group by i.itemId

注:考虑前缀列<代码>附录< /代码>在<代码> < /Cult>子句及其表,以避免歧义。

我认为这是我想要的,除了它的特性。级别和不是Max升级,我也不理解“<代码> 1个0个/<代码>”真的意思是一样的。“
then maxUpgrade end
”,您能给我解释一下它们的用途吗?@SamyPereger:每当满足某个级别属于给定范围的字符时,
sum()
就会递增(
then 1 else 0 end
)。这与
maxUpgrade
的平均值的逻辑相同:
case
表达式返回
maxUpgrade
,如果玩家的级别属于该范围,则返回
null
,而
avg()
忽略该值。
select i.itemId,
    sum(case when c.level between  1 and 10 then 1 else 0 end) as use_1_10,
    avg(case when c.level between  1 and 10 then maxUpgrade end) as avg_level_1_10,
    sum(case when c.level between 11 and 20 then 1 else 0 end) as use_11_20,
    avg(case when c.level between 11 and 20 then maxUpgrade end) as avg_level_11_20,
    ...
from items i 
inner join characters c on i.characterId = c.characterId 
where i.itemid in (...)  and attached > 0
group by i.itemId