Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server CASE语句解决方案,用于在一组ID内设置值_Sql Server_Tsql - Fatal编程技术网

Sql server CASE语句解决方案,用于在一组ID内设置值

Sql server CASE语句解决方案,用于在一组ID内设置值,sql-server,tsql,Sql Server,Tsql,我在GamePlayers表中有以下数据: GameId PlayerId BotId 1 100 NULL 1 200 NULL 2 100 NULL 2 NULL NULL 3 200 NULL 3 NULL 100 我想报告玩的人类/计算机/机器人游戏的百分比。电脑游戏和机器人游戏是分开处理的。如果我把它写进一

我在GamePlayers表中有以下数据:

GameId   PlayerId  BotId           
1        100       NULL
1        200       NULL
2        100       NULL
2        NULL      NULL
3        200       NULL
3        NULL      100
我想报告玩的人类/计算机/机器人游戏的百分比。电脑游戏和机器人游戏是分开处理的。如果我把它写进一个案例陈述中,它会很简单

CASE  WHEN PlayerId IS NOT NULL THEN 'Human'
      WHEN PlayerId IS NULL AND BotId IS NULL THEN 'Computer'
      WHEN PlayerId IS NULL AND BotId IS NOT NULL THEN 'Bot'
      END OpponentType
当然,为了删除重复的GameId,我需要按GameId对数据进行分组

计算机和机器人永远不能相互对抗。一个人可以挑战一个人,但是如果他在30秒后没有得到回复,他就可以和一个机器人比赛。人类也可以选择单独与计算机比赛

我需要做的是为一组“人”、“机器人”或“计算机”设置一个值,然后在Power BI上报告它。我如何对数据进行分组,以确定人类对手是否与人类、机器人或计算机对抗

这是我的预期结果集:

GameId   GameType         
1        Human
2        Computer
3        Bot

我使用您的查询如下:

Select GameId, 
    case when max(OpponentType) = mIn(opponenttype) and Min(opponenttype) = 'Human' then 'Human' 
        when min(opponenttype) = 'Computer' then 'Computer'
        when min(opponenttype) = 'Bot' then 'Bot' else null end as OpponentType 
    from ( Select GameId , CASE  WHEN PlayerId IS NOT NULL THEN 'Human'
  WHEN PlayerId IS NULL AND BotId IS NULL THEN 'Computer'
  WHEN PlayerId IS NULL AND BotId IS NOT NULL THEN 'Bot'
  END OpponentType
  from #Game ) a
group by gameid

您不需要在子查询中执行opponenttype,而是可以在主查询中执行此操作

您可以在分组中按查询使用case,如下所示

 select 
       gameId, 
       case 
          WHEN count(PlayerId)=2 THEN N'Human'
          WHEN count(BotId) =1 THEN N'Bot'
          WHEN count(BotId) =0 AND count(PlayerId)=1 THEN 'Computer'
          END as OpponentType
    from GamePlayers  group by GameId 

你的结果必须是2和3 GAMIDID?你能加上你预期的结果集吗?@ KANANKANDANASAMY道歉,只是你决定如何考虑哪一行?@ RaJ这是我所面临的问题,我不确定如何把计算机/BOT优先于人类游戏完美,谢谢!与@KannanKandasamy的答案相比,我更喜欢这个答案的简单,但是他的作品too@Powellellogram很高兴我的回答有用。