我正面临一个问题,我无法理解什么是错的。
在我的数据库中,我有一个datetime
字段,它保留了一些值:03.10.2012 11:25:06
我需要将其转换为date
并将其与其他日期进行比较。我没有成功的尝试是:
p1.value as City,
p2.value as Country,
p3.value as RequestNumber,
convert (datetime, convert (varchar, test.timestampmin, 101), 101) as timestampmin
from Process p
LEFT JOIN Parameter p1 on p1.ID=p.id AND p1.NAME = 'City'
LEFT JOIN Parameter p2 on p2.ID=p.id AND p2.NAME = 'Country'
LEFT JOIN PA_Parameter p3 on p3.ID=p.id AND p3.NAME = 'RequestNumber'
INNER JOIN
(
SELECT min(Timestamp) as timestampmin, id as id
FROM tasks
GROUP BY id
) as test
ON test.id = p3.ID
where p.type='Event' and
timestampmin = convert (datetime, convert (varchar, '06.18.2012', 101), 101)
问题在于我无法将转换后的datetime
与我在where子句中使用的convert (datetime, convert (varchar, '06.18.2012', 101), 101)
进行比较。
我错过了什么?
答案 0 :(得分:1)
很简单,您无法在同一查询的WHERE子句中的SELECT子句中访问列别名。
p1.value as City,
p2.value as Country,
p3.value as RequestNumber,
convert (datetime, convert (varchar, test.timestampmin, 101), 101) as timestampmin
from Process p
LEFT JOIN Parameter p1 on p1.ID=p.id AND p1.NAME = 'City'
LEFT JOIN Parameter p2 on p2.ID=p.id AND p2.NAME = 'Country'
LEFT JOIN PA_Parameter p3 on p3.ID=p.id AND p3.NAME = 'RequestNumber'
INNER JOIN
(
SELECT min(Timestamp) as timestampmin, id as id
FROM tasks
GROUP BY id
) as test
ON test.id = p3.ID
where p.type='Event' and
convert (datetime, convert (varchar, test.timestampmin, 101), 101)
= convert (datetime, convert (varchar, '06.18.2012', 101), 101)
如果test.timestampmin
是日期时间列,则可以在WHERE子句中使用它
where p.type='Event'
and test.timestampmin >= '20120618'
and test.timestampmin < '20120619'