1

我正在摆弄创建子查询只是为了习惯它们。如果某人的 ID 在联结表中出现 X 次,我正在尝试获取一个人的 ID# 和相关费用。我试过了

select id, charges from myTable
where id in
(
    select id from jxnTable
having (count(jxn.id> 10))
group by jxn.id

这给了我错误jxn.id is invalid in the select list because it is not contained in either an aggregate function of a group by clause.

4

2 回答 2

2

除了您的子句中的一些奇怪之外,您GROUP BY属于子查询。()HAVING

select id, charges from myTable
where id in
(
    select id from jxnTable
    GROUP BY id
    having (count(id>) 10)
)

这也可以通过JOIN针对子查询而不是IN()子句来完成,这可能更快:

SELECT m.id, charges
FROM myTable M
  INNER JOIN (
    SELECT id FROM jxnTable
    GROUP BY id
    HAVING COUNT(id) > 10
  ) cnt  ON m.id = cnt.id
于 2012-05-17T18:27:00.877 回答
2

三个错误:

  • GROUP BY 和 HAVING 必须是同一查询的一部分,并且 GROUP BY 必须以文本形式出现在相应的 HAVING 之前。
  • COUNT 表达式周围的括号不正确。
  • 您没有名为 的表或别名jxn

试试这个:

SELECT id, charges
FROM myTable
WHERE id IN
(
    SELECT id
    FROM jxnTable
    GROUP BY id
    HAVING COUNT(id) > 10
)
于 2012-05-17T18:27:13.877 回答