简体   繁体   English

SQL-带计数的从子句嵌套选择

[英]SQL - Nested Select in From claus with Count

When I use the following code (it is from an Oracle guy and he says there is no reason for it not to work...) I am notified that there is incorrect syntax located at the last ')'. 当我使用以下代码(来自Oracle的人,他说没有理由不起作用...)时,系统会通知我,最后一个')'语法不正确。 Any idea how I can change this to be "SQL Appropriate"? 知道如何将其更改为“ SQL适当的”吗? My thoughts are that it is not liking the last select statement. 我的想法是它不喜欢最后一个选择语句。

select 
    * 
from 
    CPINInvest 
where 
    [Case ID||] not in 
        (
        select [Case ID||] 
        from 
            (
            select [Case ID||], count(*) 
            from CPINComm140 
            where [Role CD||]='PRI||' 
            group by [Case ID||]   
            having count(*)=1
            )
        )

It can be shortened. 可以缩短。

select * from CPINInvest 
where [Case ID||] not in (
        select [Case ID||]
        from CPINComm140 
        where [Role CD||]='PRI||' 
        group by [Case ID||] 
        having count(*)=1
    );

But seriously, pipes in fieldnames? 但是认真的说,字段名中的管道? Yuk! k!

The reason why the original query would fail is: 原始查询失败的原因是:
1) the count(*) needs an alias. 1)count(*)需要一个别名。 For example [total] 例如[总计]
2) tsql has that odd requirement that some subqueries require an alias 2)tsql有一个奇怪的要求,即某些子查询需要别名

sql likes you to give aliases to your sub-queries even if they are not used. sql希望您为子查询提供别名,即使不使用别名也是如此。 This will work but @LukStorms shorter version is better. 这将起作用,但@LukStorms较短的版本更好。

select * 
from CPINInvest 
where 
    [Case ID||] not in 
        (
        select [Case ID||] 
        from 
            (
            select [Case ID||], count(*) 
            from CPINComm140 
            where [Role CD||]='PRI||' 
            group by [Case ID||]   
            having count(*)=1
            ) x
        ) y

use the below query. 使用以下查询。 You have forgot to add alias to the sub table. 您忘记为子表添加别名。

select 
    * 
from 
    CPINInvest 
where 
    [Case ID||] not in 
        (
        select [Case ID||] 
        from 
            (
            select [Case ID||], count(*) 
            from CPINComm140 
            where [Role CD||]='PRI||' 
            group by [Case ID||]   
            having count(*)=1
            )t
        )

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

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