如何修复“仅当子查询未引入EXISTS时,在选择列表中只能指定一个表达式”错误?

4

我的查询如下,并且其中包含一个子查询:

select a.bill_prvdr_acct_id, a.acct_id, a.bill_prvdr_acct_strt_dt, a.bill_prvdr_acct_end_dt
from xxxx_snapshot.dbo.bill_prvdr_acct_history a
where a.acct_id in 
(select acct_id, count(*)
from xxxx_snapshot.dbo.bill_prvdr_acct_history 
group by acct_id
having count(*) > 1)

我收到了错误信息:“当子查询没有使用EXISTS引入时,仅可以在选择列表中指定一个表达式。”


2
摆脱在SELECT语句中使用count(*)作为查询值。 - OldProgrammer
1
你使用的是哪个数据库? - Gordon Linoff
4个回答

3

考虑到您的查询结构,窗口函数可能是实现您想要的功能更为简单的方法:

select a.bill_prvdr_acct_id, a.acct_id, a.bill_prvdr_acct_strt_dt, a.bill_prvdr_acct_end_dt
from (select a.*, count(*) over (partition by acct_id) as cnt
      from xxxx_snapshot.dbo.bill_prvdr_acct_history a
     ) a
where cnt > 1;

2

Count(*) 在子查询的 SELECT 子句中并非必需,只需要在 HAVING 子句中使用即可 - 以下代码应该可以正常工作:

select a.bill_prvdr_acct_id, a.acct_id, a.bill_prvdr_acct_strt_dt, a.bill_prvdr_acct_end_dt
from xxxx_snapshot.dbo.bill_prvdr_acct_history a
where a.acct_id in 
(select acct_id
from xxxx_snapshot.dbo.bill_prvdr_acct_history 
group by acct_id
having count(*) > 1)

2

错误是由子查询中选择多个列引起的。

当您在where子句中使用IN运算符时,不能在subquery中选择多个列。

如错误所述,请使用EXISTS或从subquery中删除不需要的count(*)

SELECT a.bill_prvdr_acct_id,
       a.acct_id,
       a.bill_prvdr_acct_strt_dt,
       a.bill_prvdr_acct_end_dt
FROM   xxxx_snapshot.dbo.bill_prvdr_acct_history a
WHERE  EXISTS (SELECT 1
               FROM   xxxx_snapshot.dbo.bill_prvdr_acct_history b
               WHERE  a.acct_id = B.acct_id
               GROUP  BY acct_id
               HAVING Count(*) > 1) 

或者进行 内连接

SELECT a.bill_prvdr_acct_id,
       a.acct_id,
       a.bill_prvdr_acct_strt_dt,
       a.bill_prvdr_acct_end_dt
FROM   xxxx_snapshot.dbo.bill_prvdr_acct_history a
       INNER JOIN (SELECT acct_id
                   FROM   xxxx_snapshot.dbo.bill_prvdr_acct_history b
                   GROUP  BY acct_id
                   HAVING Count(*) > 1) B
               ON a.acct_id = B.acct_id 

0

为了简化一切,请先独立运行您的查询,以确保只返回一列:

select acct_id
from xxxx_snapshot.dbo.bill_prvdr_acct_history 
group by acct_id
having count(*) > 1
Above you are returning the acct_id

如果它能带回所需的结果,就将其包含在主查询中:
SELECT a.bill_prvdr_acct_id,
       a.acct_id,
       a.bill_prvdr_acct_strt_dt,
       a.bill_prvdr_acct_end_dt
FROM   xxxx_snapshot.dbo.bill_prvdr_acct_history a
WHERE  a.acct_id IN (select acct_id
from xxxx_snapshot.dbo.bill_prvdr_acct_history 
group by acct_id
having count(*) > 1) 

这样做将很容易确认子查询是否返回单个列和所需的结果,并将其链接到主查询中,如果主查询存在问题,则会更容易解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接