我在4个数据库中有4个表,并希望通过今天上午6:00至次日上午6:00的唯一ID和日期时间对最大值进行过滤,并输出为另一个表/ view。
我厌倦了按此要求加入餐桌。
USE PLC_WTR1
GO
SELECT PLCTAG_PLC1_WTR1S001_PCReadJob_Tar_JobNo_Value,
MAX (Section_WTR1S001_CurrentJob_BatchLog_WeightActualProduced_Value) FROM WTR1
WHERE CAST (DateAndTime AS time) >= '05:59:00.000'
OR CAST (DateAndTime AS time) <= '05:59:00.000'
GROUP BY PLCTAG_PLC1_WTR1S001_PCReadJob_Tar_JobNo_Value
USE PLC_WTR2
GO
SELECT PLCTAG_PLC1_WTR2S001_PCReadJob_Tar_JobNo_Value,
MAX (Section_WTR2S001_CurrentJob_BatchLog_WeightActualProduced_Value) FROM WTR2
WHERE CAST (DateAndTime AS time) >= '05:59:00.000'
OR CAST (DateAndTime AS time) <= '05:59:00.000'
GROUP BY PLCTAG_PLC1_WTR2S001_PCReadJob_Tar_JobNo_Value
USE PLC_WTR3
GO
SELECT PLCTAG_PLC1_WTR3S001_PCReadJob_Tar_JobNo_Value,
MAX (Section_WTR3S001_CurrentJob_BatchLog_WeightActualProduced_Value) FROM WTR3
WHERE CAST (DateAndTime AS time) >= ' 05:59:00.000'
OR CAST (DateAndTime AS time) <= '05:59:00.000'
GROUP BY PLCTAG_PLC1_WTR3S001_PCReadJob_Tar_JobNo_Value
USE PLC_WTR4
GO
SELECT PLCTAG_PLC1_WTR4S001_PCReadJob_Tar_JobNo_Value,
MAX (Section_WTR4S001_CurrentJob_BatchLog_WeightActualProduced_Value) FROM WTR4
WHERE DateAndTime >= '2019-04-17 05:59:00.000'
OR DateAndTime <= '2019-04-18 05:59:00.000'
GROUP BY PLCTAG_PLC1_WTR4S001_PCReadJob_Tar_JobNo_Value
答案 0 :(得分:0)
您可以将数据库和 schema 名称放在表名称的开头。可能您想要一个union
结果。另一点是,您只过滤时间部分的 ,因此它将带其他几天(今天除外)的行以及具有相同时间的行。
以下是如何在1个查询中使用多个数据库的示例,
select col1 from database1.dbo.table1
union all
select col1 from database2.dbo.table2
请注意,我正在使用dbo
模式。