簡體   English   中英

SQL Server-將DATEDIFF與子查詢列一起使用

[英]SQL SERVER - Using DATEDIFF with subquery column

我有一個查詢,看起來像:

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

但是,DATEDIFF行不喜歡別名列。

簡而言之,如何給DATEDIFF一個由子查詢派生的別名列?

使用派生表概念來訪問別名。

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
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM