0

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?

1
  • you can't use column alias in where clause. That's the error. Commented May 22, 2012 at 14:11

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Hmmm... So I can use column names but not column aliases in a where clause? Your query worked once I changed 'cli' to 'cl1' in the second 'from'... thanks; that gets me started on my real query.
0

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 + '-%'
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.