【问题标题】:I am getting a "subquery returning multiple rows" error. I want to return multiple rows however我收到“子查询返回多行”错误。但是我想返回多行
【发布时间】:2020-04-24 18:15:56
【问题描述】:

我想要一个在 MySQL 中返回多行的子查询。我也使用了 IN 函数。但是我收到“子查询返回多行”错误。我附上了一张使用的表格和所需输出的图像 这是我的 SQL 代码:

Select t2.STUID, t3.UnitCmd, //main query

(Select count(*) as 'FullDutyCount' from stormtroopers_officer A1 inner join st_officer_assign A2 ON A1.STID = A2.STID where A2.STUID IN('STU-1','STU-2','STU-3') AND A1.DutyStatus = 'Full Duty' group by A1.Dutystatus,A2.STUID), //subquery1

(Select count(*) as 'WoundedCount' from stormtroopers_officer A1 inner join st_officer_assign A2 ON A1.STID = A2.STID where A2.STUID IN('STU-1','STU-2','STU-3') AND A1.DutyStatus = 'Wounded' group by A1.Dutystatus,A2.STUID),//subquery2

(Select count(*) as 'KilledCount' from stormtroopers_officer A1 inner join st_officer_assign A2 ON A1.STID = A2.STID where A2.STUID IN('STU-1','STU-2','STU-3') AND A1.DutyStatus = 'Killed' group by A1.Dutystatus,A2.STUID) //subquery 3

FROM stormtroopers_officer t1 inner join st_officer_assign t2 ON t1.STID = t2.STID
inner join stormtrooper_unit t3 ON t2.STUID = t3.STUID where t2.STUID IN ('STU-1','STU-2','STU-3') group by t1.Dutystatus,t2.STUID;

【问题讨论】:

    标签: mysql sql join group-by pivot


    【解决方案1】:

    你似乎想要条件聚合:

    select
        su.stuid,
        su.unitCmd unitHQ,
        sum(so.dutyStatus = 'Full Duty') fullDutyCount,
        sum(so.dutyStatus = 'Wounded'  ) woundedCount,
        sum(so.dutyStatus = 'Killed'   ) killedCount
    from st_officier_assign soa
    inner join stormtrooper_unit su on su.stuid = soa.stuid
    inner join stormtrooper_officer so on so.stid = so.stid
    where su.stuid in ('STU-1','STU-2','STU-3')
    group by su.stuid, su.unitCmd
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      相关资源
      最近更新 更多