So I have the SQL statement below and it works:
SELECT T1.*,
(SELECT COUNT(T3.CTransaction) FROM GBTransaction T3
WHERE T3.CSite = 'Store'
and T3.CTransactionType = 'Release'
and T3.CReference = T1.CTransaction) as releasecount
FROM GBTransaction T1
where T1.CSite = 'Store'
and T1.CTransactionType = 'Layaway'
and T1.CStatus = 'Active'
and T1.CBalance <= 0
order by T1.CBalance, T1.CDueDate, T1.CTransaction
Basically I'm determining if there is a reference record existing through (SELECT COUNT(T3.CTransaction) FROM GBTransaction T3 WHERE T3.CSite = 'Store' and T3.CTransactionType = 'Release' and T3.CReference = T1.CTransaction) as releasecount
But if I add another WHERE condition which is AND releasecount > 0
, SQL Server says
Invalid column name releasecount
.
The final statement including the added WHERE condition is the one below:
SELECT T1.*,
(SELECT COUNT(T3.CTransaction) FROM GBTransaction T3
WHERE T3.CSite = 'Store'
and T3.CTransactionType = 'Release'
and T3.CReference = T1.CTransaction) as releasecount
FROM GBTransaction T1
where T1.CSite = 'Store'
and T1.CTransactionType = 'Layaway'
and T1.CStatus = 'Active'
and T1.CBalance <= 0
and releasecount > 0
order by T1.CBalance, T1.CDueDate, T1.CTransaction
I'm confused and have no idea why it doesn't work? Thank you so much.