2012-12-08 84 views
1

可能重複:
Distinct in SQL Server爲什麼distinct在這個sql查詢中不起作用? - 複雜的查詢

我想選擇disctinct 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

非常感謝您的答案

+0

我沒有看到任何重複的行......你認爲哪些是重複的,應該由'DISTINCT'消除? 'DISTINCT'只適用於'SELECT'中的** ALL **列 - 只有當所有值相同時纔會排除一行。 –

+0

,因爲它們不會在所有列中重複,例如'maxlevel'各不相同 – codingbiz

+0

@marc_s哦,我明白了。無論如何,我可以讓PokemonIds獨特嗎? – MonsterMMORPG

回答

1

你不應該在你的GroupBy條款MaxLevel。這樣做:

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 
+0

工作得很好。你能解釋背後的邏輯嗎? – MonsterMMORPG

+0

您可能知道,distinct會刪除完全相同的行,但是當您在Group by子句中包含MaxLevel時,它會使行不同,因此Distinct不起作用。 –