表达非布尔类型

时间:2010-12-14 19:43:10

标签: sql sql-server tsql sql-server-2008

使用此声明:

select * from qvalues where rowid ,name,compound in (
    select rowid,name,compound from qvalues where rowid in (select rowid from batchinfo where instrument='tf1')
    group by rowid,name,compound
    having COUNT(*)>1 
    )
    group by rowid,name,compound
having rid=min(rid)

发生此错误:

  

Msg 4145,Level 15,State 1,Line 3   在预期条件的上下文中指定的非布尔类型的表达式,靠近','。   Msg 156,Level 15,State 1,Line 8   关键字“group”附近的语法不正确。

这个SQL语句有什么问题?我需要在表having min(rid)中找到这三个字段的所有匹配项。

更新 使用此查询,外部选择不起作用。我做错了什么?

select * from qvalues where rid not in (
select q.rowid, q.name, q.compound, min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1)

2 个答案:

答案 0 :(得分:2)

我认为这相当于你想要实现的目标。

select min(q.rid)
    from qvalues q
        inner join batchinfo b
            on q.rowid = b.rowid
                and b.instrument = 'tf1'
    group by q.rowid, q.name, q.compound
    having count(*) > 1

答案 1 :(得分:1)

最终having min(rid)需要进行比较

如果你重新安排你的代码片段,就没有关联的GROUP BY,你可以看到

select * from qvalues
where rowid ,name,compound in (
               select rowid,name,compound from qvalues
               where rowid in (select rowid from batchinfo where instrument='tf1')
               group by rowid,name,compound
               having COUNT(*)>1 
               )
--missing group by
having min(rid) -- > foo

编辑:重新制定:

select
   *
from
    (
    select
       rowid,name,compound, min(q.rid) as minrid
    from
       qvalues q
    where
       EXISTS (SELECT * FROM batchinfo b where b.instrument='tf1' AND b.rowid = q.rowid)
    group by
        rowid,name,compound
    having
        COUNT(*)>1
    ) foo
    JOIN
    qvalues q2 On foo.rowid = q.rowid AND foo.name = q.name AND foo.compound = q.compound
                   AND foo.minrid = q2.rid

原始错误可能来自缺少派生表的别名,再加上SQL Server不支持多列IN的事实。我使用EXISTS而不是JOIN,因为你可能会从qvalues JOIN batchinfo获得比你预期更多的行(基于Joe的回答)