0

I am trying to find data of One Table where Weeks column is greater than result of Subquery.But somehow that is not running due to Incorrect syntax

SELECT * FROM Table1 a WHERE CONVERT(DATE,SUBSTRING(a.WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)>
(SELECT MAX(x.WEEKS) AS MONTHLY_MAX_WEEKS FROM
(
(SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS  FROM Table2 
UNION ALL
SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS FROM Table3 
) AS x))
2
  • 2
    You already have a solution, but for situations like this, try breaking down and running each part of your query separately first to see if they run. That can help track down the error. Then start combining them slowly to find the error. This approach works good for testing logic as well, test each part FIRST then combine them. Commented Feb 16, 2021 at 13:53
  • Do you really need a subquery with a subquery in it? Commented Feb 16, 2021 at 14:01

2 Answers 2

2

You should change like this

SELECT * FROM Table1 a WHERE CONVERT(DATE,SUBSTRING(a.WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)>
(
SELECT MAX(x.WEEKS) AS MONTHLY_MAX_WEEKS 
FROM
(
  (SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS  FROM Table2 
  UNION ALL
  SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS FROM Table3 
  ) 
)as x
)
Sign up to request clarification or add additional context in comments.

Comments

2

You should remove some AS

SELECT * 
FROM Table1 a 
WHERE CONVERT(DATE,SUBSTRING(a.WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1) >
(SELECT MAX(x.WEEKS) AS MONTHLY_MAX_WEEKS 
    FROM (
    SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS  FROM Table2 
    UNION ALL
    SELECT MAX(CONVERT(DATE,SUBSTRING(WEEKS,CHARINDEX('W/E',WEEKS)+4,12),1)) AS WEEKS FROM Table3 
) t  ) 

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.