0

我面临一个奇怪的问题,我不明白出了什么问题。在我的数据库中,我有一个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后的值与convert (datetime, convert (varchar, '06.18.2012', 101), 101)我在 where 子句中使用的值进行比较。

我错过了什么?

4

1 回答 1

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'
于 2012-11-28T07:30:58.397 回答