简体   繁体   中英

count/select query in MS Sql Server 2005

I have a legacy table that contains 'master' records and associated detail records. Detail records are identified by an addition to the master key of "-nnn". I need to find master records that have no detail records, tried several variations, and then finally broke it down to simplest elements.

This works:

select (select count(*) from dbo.client as cl2 
    where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no 
from dbo.client as cl1

and displays the expected zero or non-zero results, depending on how many detail records there are.

However, when I try to use the count results to select only the records with zero detail records, like so:

select (select count(*) from dbo.client as cl2 
    where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no 
from dbo.client as cl1 
where countx = 0

I get an error: "Invalid column name 'countx'"

What am I missing here?

CountX is not a named column.

This may not be the most optimal way, but wrapping the entire query might work.

SELECT CountX, Acct_No
FROM
(
    select (select count(*) from dbo.client as cl2 
        where cl2.acct_no like (cl1.acct_no + '-%')) as countx, acct_no 
    from dbo.client as cli
) As InnerQuery
where countx = 0

Edit

Looking at this, it may be better Accomplished using a Join, instead of that nested Select.

SELECT     cl1.acct_no, Count(*)
FROM       dbo.client cl1 --the master key numbers
INNER JOIN dbo.client cl2 --the sub-keys
           ON cl1.acct_no NOT LIKE '%-%' --No dashes in the MasterKey
           AND cl1.acct_no LIKE (cl2.acct_no + '-%')
GROUP BY   cl1.acct_no

Try using in to get what you want

 select Acct_No from dbo.client where Acct_No not in 
  (
    select acct_no from dbo.client where acct_no like acct_no + '-%'
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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