0

I have a query that looks like:

SELECT
    col1
    ,...
    ,col3
    ,(SELECT col3 FROM table where <clause>) AS MinPickTime
    ,(SELECT col3 FROM table where <clause>) AS MaxPickTime
    ,DATEDIFF(d, MinPickTime, MaxPickTime)
FROM table

However the DATEDIFF line does not like the alias columns.

In short, how do I give DATEDIFF an alias column derived by a subquery?

2 Answers 2

1

Use derived tables concept to access alias name.

SELECT  col1
    ,...
    ,col3,
     MinPickTime,
     MaxPickTime ,
DATEDIFF(d, MinPickTime, MaxPickTime)
FROM (
SELECT
    col1
    ,...
    ,col3
    ,(SELECT col3 FROM table where <clause>) AS MinPickTime
    ,(SELECT col3 FROM table where <clause>) AS MaxPickTime

FROM table
)z
Sign up to request clarification or add additional context in comments.

1 Comment

0
with temp as (SELECT
    col1
    ,...
    ,col3
    ,(SELECT col3 FROM table where <clause>) AS MinPickTime
    ,(SELECT col3 FROM table where <clause>) AS MaxPickTime
FROM table)

select DATEDIFF(d,MaxPickTime,MinPickTime) from temp

1 Comment

It is always more helpful if you explain how your code works.

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.