为什么此子查询只返回一条记录?

时间:2014-09-15 22:08:57

标签: sql

这是我的子查询。我很难理解为什么这会不断地回到我身边说(“这个子查询最多只能返回一条记录”)

SELECT COUNT(*)
FROM SoftwareAssigned
GROUP BY SoftID

根据我的理解,这是说“获取SoftID(softwareID)相同的所有记录的数量”

真正发生了什么,以及如何避免将来犯这个错误?

上下文属于此(尝试查询:)

SELECT Software.Description, Software.QtyPurchased
, (
  SELECT COUNT(*)
  FROM SoftwareAssigned
  GROUP BY SoftID
) AS Assigned
,( Software.QtyPurchased - 
  (
    SELECT COUNT(*)
    FROM SoftwareAssigned
    GROUP BY SoftID
  ) 
) AS Remaining
FROM Software
;

2 个答案:

答案 0 :(得分:1)

查询将"获取每个特定SoftID值的计数,其中有多少具有该ID"。

对于表中存在的每个特定SoftID值,查询将返回一行。

如果要计算有多少不同的SoftID值,可以使用:

select count(distinct SoftID)
from SoftwareAssigned

编辑:

要从一个记录表中获取与另一个表中的记录对应的计数,您可以将这些表连接在一起并对另一个表中的值进行分组:

select
  Software.Description, Software.QtyPurchased,
  count(SoftwareAssigned.SoftID) as Assigned,
  Software.QtyPurchased - count(SoftwareAssigned.SoftID) as Remaining
from
  Software
  left join SoftwareAssigned on SoftwareAssigned.SoftID = Software.SoftID
group by
  Software.SoftID, Software.Description, Software.QtyPurchased

答案 1 :(得分:0)

我假设Sofware有一个SoftID列。看起来你希望SQL将在子查询和主查询之间建立链接。只有当你告诉它如何时才会这样做:

select
    s.Description,
    s.QtyPurchased, (
        select
            count(*)
        from
            SoftwareAssigned a
        where
            -- link to outer query
            a.SoftID = s.SoftID
    ) as Assigned,
    s.QtyPurchased - (
        select
            count(*)
        from
            SoftwareAssigned a
        where
            -- link to outer query.
            a.SoftID = s.SoftID
    ) as Remaining
from
    Software s;

碰巧,有一种更紧凑的写作方式:

select
    s.Description,
    s.QtyPurchased,
    count(a.SoftID) as assigned,
    s.QtyPurchased - count(a.SoftID) as Remaining
from
    software s
        left outer join
    SoftwareAssigned a
        on s.SoftID = a.SoftID
group by
    s.SoftID,
    s.Description,
    s.QtyPurchased;

Example SQLFiddle