简体   繁体   English

子查询在我的SQL查询中返回多于1行

[英]Subquery returns more than 1 row in my SQL query

I am trying to create an SQL query that displays some information from different tables. 我正在尝试创建一个SQL查询,该查询显示来自不同表的一些信息。 But I'm getting the error Subquery returns more than 1 row SQL. 但是我收到错误子查询返回多于1行的SQL。 I want it to display more than one row. 我希望它显示多于一行。

    SELECT  c.Name,
        jn.ID,
        jn.ActualWeight as GrossWt,
        jn.JobNo,
        COUNT(distinct jn.JobNo) as Jobs,
        COUNT(distinct jd.JobID) as Dbriefs,
        COUNT(distinct jn.OutTurn) as Outturns,
        (select Status from jobstat where CompanyID = jn.CompanyID AND Status = "DEL") as Delivery
FROM job_new jn
LEFT JOIN customer c ON  jn.CompanyID = c.Company_ID
LEFT JOIN job_debriefs jd ON jn.JobNo = jd.JobID
LEFT JOIN jobstat js ON jn.CompanyID = js.CompanyID
WHERE jn.CompanyID = 36

I've tried adding GROUP BY and ORDER BY but that doesn't work either. 我试过添加GROUP BY和ORDER BY,但这也不起作用。 If I remove the select State.... line it only displays one row when it should be displaying over a hundred 如果删除select State ....行,则在应显示一百以上时仅显示一行

You need a group by : 您需要一个group by

SELECT c.Name, jn.ID, jn.ActualWeight as GrossWt, jn.JobNo,
       COUNT(distinct jn.JobNo) as Jobs,
       COUNT(distinct jd.JobID) as Dbriefs,
       COUNT(distinct jn.OutTurn) as Outturns,
       jobstat
FROM job_new jn LEFT JOIN
     customer c
     ON jn.CompanyID = c.Company_ID LEFT JOIN
     job_debriefs jd
     ON jn.JobNo = jd.JobID LEFT JOIN
     jobstat js
     ON jn.CompanyID = js.CompanyID 
WHERE jn.CompanyID = 36
GROUP BY c.Name, jn.ID, jn.ActualWeight as GrossWt, jn.JobNo, js.status

I'm not sure what the subquery is supposed to be doing, so I'm guessing with regards to js.status . 我不确定子查询应该做什么,所以我在猜测js.status

The problem with your original query is the use of COUNT() in the SELECT . 您原始查询的问题是在SELECT使用了COUNT() This turns the query into an aggregation query. 这会将查询变成聚合查询。 Without a GROUP BY , exactly one row is returned. 如果没有GROUP BY ,则仅返回一行。 In most other databases, you would normally get an error. 在大多数其他数据库中,通常会出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM