想要在大型选择查询中合并具有相同ID的行

时间:2016-02-22 21:18:27

标签: sql group-by sql-server-2014

我在几张桌子上有一个很大的选择查询,近50个字段。部分原因是检查用户是否是学习者,管理员等。正如您在下面看到的那样,它返回了多行。现在我想将它们聚合成一行,基本上是一个或操作。

编辑1:每个bool值都是使用单个字段

中的case语句派生的
aRes = FightAttackersResults.loadFromFile(new File("FightSimulation-Attackers-A200-D200.obj"));
dRes = FightDefendersResults.loadFromFile(new File("FightSimulation-Defenders-A200-D200.obj"));

for (int a = defenders; a <= attackers; ++a) {
            double chance = aRes.getAttackersWinChance(a, defenders);
            if (chance >= winProbability) {
                return a;
            }
        }

到此

User ID | Learner | Admin | Facilitator | Advisor
1   0   0   0   1
1   0   1   0   0
2   0   0   1   0
3   0   0   1   0
3   0   1   0   0

添加GROUP BY UserID会出错

User ID | Learner | Admin | Facilitator | Advisor 1 0 1 0 1 2 0 0 1 0 3 0 1 1 0

我可能可以在每个字段周围包裹MAX,但这不是一个很好的查询,我认为必须有更好的方法来做到这一点

这是在MS SQL 2014中

由于

2 个答案:

答案 0 :(得分:1)

你可以在聚合查询和表#34;用户&#34;之间进行连接,如下所示:

SELECT users.userid
    ,users.firstName
    ,tMax.learner
    ,tMax.admin
    ,tMax.facilitator
    ,tMax.advisor
FROM users 
inner JOIN (select userid,
            max(learner) as learner, max(admin) as admin,
            max(facilitator) as facilitator, max(advisor) as advisor
        from t
        group by userid) AS tMax ON tmax.userId = users.userId

答案 1 :(得分:0)

您可以使用聚合执行此操作:

select userid,
       max(learner) as learner, max(admin) as admin,
       max(facilitator) as facilitator, max(advisor) as advisor
from t
group by userid;

编辑:

SQL Server没有 bool 作为数据类型。如果您的意思是bit,那么您可以使用条件逻辑:

select userid,
       max(cast(learner as int)) as learner, max(cast(admin as int)) as admin,
       max(cast(facilitator as int)) as facilitator, max(cast(advisor as int)) as advisor
from t
group by userid;