这是我的陈述:
SELECT
C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
DateAdd(dd, -1, C.ExpirationDate) as RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
WHERE (RealExpirationDate BETWEEN @StartDate AND @EndDate)
AND C.Type IN(10,15,17,25)
我一直收到错误消息,指出RealExpirationDate
是无效的列名。我该如何引用该别名?
答案 0 :(得分:5)
您不能在上面的代码中,记住WHERE
之前发生SELECT
,所以您必须使用:
WHERE DateAdd(dd, -1, C.ExpirationDate) BETWEEN @StartDate AND @EndDate
最常见的别名方法是内部视图/查询,如下所示:
SELECT
n.FooBar, --here we can use FooBar
t.BarFoo
FROM
MyTable t
INNER JOIN
(
SELECT
myTestCase as FooBar
From MyTable2
) n
答案 1 :(得分:2)
在这种情况下,您实际上不应该尝试重用别名。它不是可以攻击的(不能在ExpirationDate
上进行范围搜索。)
只需使用
WHERE C.ExpirationDate
BETWEEN DateAdd(dd, 1, @StartDate) AND DateAdd(dd, 1, @EndDate)
答案 2 :(得分:1)
您无法引用别名。您的查询必须是
SELECT
C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
DateAdd(dd, -1, C.ExpirationDate) as RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
WHERE (DateAdd(dd, -1, C.ExpirationDate) BETWEEN @StartDate AND @EndDate)
AND C.Type IN(10,15,17,25)
答案 3 :(得分:1)
在SQL Server中,您可以使用CROSS APPLY
执行此操作。这比subselect简单,但我不确定是否存在性能差异。
SELECT
C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
CROSS APPLY
(SELECT DateAdd(dd, -1, C.ExpirationDate)) CrossA(RealExpirationDate)
WHERE (RealExpirationDate BETWEEN @StartDate AND @EndDate)
AND C.Type IN(10,15,17,25)
答案 4 :(得分:0)
使用:
SELECT
C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
DateAdd(dd, -1, C.ExpirationDate) as RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
WHERE (DateAdd(dd, -1, C.ExpirationDate) BETWEEN @StartDate AND @EndDate)
AND C.Type IN(10,15,17,25)
或
SELECT * from (
SELECT C.Account,
(RTRIM(N.FIRST) + ' ' + RTRIM(LTRIM(N.MIDDLE)) + ' ' + RTRIM(LTRIM(N.LAST)) + ' ' + LTRIM(N.SUFFIX)) AS OwnerName,
DateAdd(dd, -1, C.ExpirationDate) as RealExpirationDate,
C.Description,
C.Type
FROM CARD as C
INNER JOIN NAME as N ON C.Account = N.Account
WHERE C.Type IN(10,15,17,25)
) t
WHERE RealExpirationDate BETWEEN @StartDate AND @EndDate