问题
This line of code is a snippet from my select statement.
frdFreedays - DateDiff(dd,conReceiptToStock,GetDate()) As FreeDaysRemaining
Below is a snippet from my where clause
and frdFreedays - DateDiff(dd,conReceiptToStock,GetDate()) <= @intFreeDays
The question I have is how can I reference the FreeDaysRemaining column and so I can compare it to @intFreeDays
I am looking for something like this
Freedays <= @intFreeDays
回答1:
In addition to Aaron's answer, you could use a common table expression:
;with cte_FreeDaysRemaining as
(
select
frdFreedays - DateDiff(dd,conReceiptToStock,GetDate()) As FreeDaysRemaining
--, more columns
from yourtable
)
select
FreeDaysRemaining
--, more columns
from cte_FreeDaysRemaining
where FreeDaysRemaining <= @intFreeDays
回答2:
You can't reference an alias anywhere except ORDER BY. One workaround (aside from the obvious possibility of repeating the expression) is to put it in a derived table:
SELECT FreeDaysRemaining --, other columns
FROM
(
SELECT frdFreedays - DATEDIFF(DAY, conReceiptToStock, GETDATE()) AS FreeDaysRemaining
--, other columns
FROM ...
) AS x
WHERE FreeDaysRemaining <= @intFreeDays;
来源:https://stackoverflow.com/questions/9720790/referencing-a-calculated-column-in-the-where-clause-sql