0

我有这个查询,我想得到这两个查询的结果。请注意,这machine_output是我创建的视图:

SELECT DISTINCT tblcertified.employeenumber, 
                tblcertified.machinenumber 
FROM   tblcertified 
       INNER JOIN machine_output 
               ON tblcertified.machinenumber = machine_output.machinenumber 
UNION 
SELECT CONVERT (DATE, tblperiod.fromdate) AS fDate, 
       tblscheduled.employeenumber 
FROM   tblperiod 
       INNER JOIN tblscheduled 
               ON tblperiod.number = tblscheduled.number 
WHERE  tblperiod.fromdate BETWEEN Dateadd(m, -3, Getdate()) AND Getdate() 

运行上述内容时,出现以下错误

消息 241,级别 16,状态 1,第 1 行从字符串转换日期和/或时间时转换失败。

当我删除convert语句时,我也会收到此错误。

4

1 回答 1

2

第一个子查询中的第一列称为EmployeeNumber.

第二个表中的第一列正在转换为Date.

我不认为你想要一个union,但你熟悉连接。您的select列表需要与union.

如果要解决此问题,请将第一个选择更改为:

select distinct cast(NULL as date) as fDate, tblcertified.employeenumber, tblcertified.machinenumber 

第二个选择类似于:

SELECT CONVERT (DATE, tblperiod.fromdate) AS fDate, 
       tblscheduled.employeenumber , NULL

作为join,您的查询将如下所示:

SELECT DISTINCT CONVERT (DATE, tblperiod.fromdate) AS fDate, tblcertified.employeenumber, 
                tblcertified.machinenumber
FROM   tblcertified 
       INNER JOIN machine_output 
               ON tblcertified.machinenumber = machine_output.machinenumber 
       INNER JOIN tblscheduled 
               on tblscheduled.employeenumber = tblcertified.employeenumber
       INNER JOIN tblperiod
               ON tblperiod.number = tblscheduled.number 
WHERE  tblperiod.fromdate BETWEEN Dateadd(m, -3, Getdate()) AND Getdate() ;

这有点猜测你想要什么(你没有样本数据来说明清楚)。但是,您可以在一个查询中完成所有连接并提取您需要的列。

于 2013-05-07T16:10:34.743 回答