Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I need to select just one columns among those returned by a Select statement and I'm trying to use a subquery inside FROM in order to do that.

My problem is that the column is not recognized outside the subquery; on the other hands, I'm not allowed to use another FROM statement to tell the name of the table I want to use (and there is no need to do that because such FROM TableName is already inside the subquery I need to extract the column from, right?).


What I have tried:

SELECT Day(MyDate) AS MyDate
 FROM
 (
  SELECT
       TOP(10) 
       COUNT(*) AS 'total',
       day(myDate) AS 'myDay'  
  FROM tableName 
  GROUP BY Day(MyDate)
  ORDER BY 'total' 
  ) AS MyDate


Error: Invalid column name  'MyDate'
Posted
Updated 6-Nov-20 1:32am
v2
Comments
[no name] 6-Nov-20 5:48am    
You changed it to 'myDay'.
xhon 6-Nov-20 6:00am    
I edited it, but nothing changed, the column name is still invalid

1 solution

Your sub-query returns two columns: myDay and total.

There is no column called MyDate to access in your outer query.

Try:
SQL
SELECT T.myDay, T.total
FROM
(
    SELECT TOP(10) COUNT(*) AS 'total', day(myDate) AS 'myDay'  
    FROM tableName 
    GROUP BY Day(MyDate)
    ORDER BY 'total' 
) As T
However, in this instance, you don't need the outer query at all:
SQL
SELECT TOP(10) COUNT(*) AS 'total', day(myDate) AS 'myDay'  
FROM tableName 
GROUP BY Day(MyDate)
ORDER BY 'total' 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900