简体   繁体   中英

SQL Server - Using a column alias in a subquery

I have the following query which works fine with MySQL but refuses to work with SQL server:

SELECT table1.someField AS theField, 
       COUNT(table2.someField) / (SELECT COUNT(someField) FROM table1 WHERE someField = theField),
FROM table1 LEFT JOIN table2 ON table1.someField = table2.someField

SQL Server doesn't seem to like the alias in the subquery. I've been told I need to use a CTE but I've never used them before. Is this correct?

The problem might well be in the confusion in the sub-query

SELECT COUNT(someField) FROM table1 WHERE someField = theField

the someField in the condition will be local - but you can get to table1.someField just the same.

How about

SELECT COUNT(t3.someField) FROM table1 t3 WHERE t3.someField = table1.someField 

?

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