为什么distinct不能在这个sql查询中工作? - 复杂的查询

时间:2012-12-08 21:56:08

标签: sql-server select sql-server-2008-r2 distinct

  

可能重复:
  Distinct in SQL Server

我想选择不同的PokemonId变量,但它不起作用

这里是查询

select distinct top 36 
    tblFoundPokemonsOnRoutes.pokemonId,MonsterTotalStats,
    MAX(maxLevel) as maxLevel,
    Case Class WHEN 'Ancient' Then '9' 
      WHEN 'Legendary' Then '8' 
      WHEN 'Zenith' Then '7' 
      WHEN 'Emissary' Then '6' 
      WHEN 'Starter' Then '5' 
      WHEN 'Superior' Then '4' 
      WHEN 'Regular' Then '3' 
      ELSE Class 
    END as Result 
from 
    tblFoundPokemonsOnRoutes 
left join 
    tblPokedex on tblFoundPokemonsOnRoutes.pokemonId = tblPokedex.PokemonId 
where 
    tblFoundPokemonsOnRoutes.routeId in 
          (select routeId from tblRoutes where ZoneNumber = 1) 
group by 
    maxLevel, tblFoundPokemonsOnRoutes.pokemonId, MonsterTotalStats, Class 
order by 
    Result desc, MonsterTotalStats desc

返回结果

enter image description here

非常感谢答案

1 个答案:

答案 0 :(得分:1)

您不应在MaxLevel条款中包含GroupBy。这样做:

select distinct top 36 
    tblFoundPokemonsOnRoutes.pokemonId,MonsterTotalStats,
    MAX(maxLevel) as maxLevel,
    Case Class WHEN 'Ancient' Then '9' 
      WHEN 'Legendary' Then '8' 
      WHEN 'Zenith' Then '7' 
      WHEN 'Emissary' Then '6' 
      WHEN 'Starter' Then '5' 
      WHEN 'Superior' Then '4' 
      WHEN 'Regular' Then '3' 
      ELSE Class 
    END as Result 
from 
    tblFoundPokemonsOnRoutes 
left join 
    tblPokedex on tblFoundPokemonsOnRoutes.pokemonId = tblPokedex.PokemonId 
where 
    tblFoundPokemonsOnRoutes.routeId in 
          (select routeId from tblRoutes where ZoneNumber = 1) 
group by 
     tblFoundPokemonsOnRoutes.pokemonId, MonsterTotalStats, Class 
order by 
    Result desc, MonsterTotalStats desc