作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] 不同资料库 同table查询问题
时间Fri Jan 12 14:32:05 2018
方法一:
;with tb1 as (
select M.产编,T1.日期
From 资料库Now.table M
Left outer join 资料库Now.Table出货纪录 T1 on M.产编 = T1.产编
Where 条件 T1.xx = xxx.....
),
tb2 as (
select M.产编,T1.日期
From 资料库2013.table M
Left outer join 资料库2013.Table出货纪录 T1 on M.产编 = T1.产编
Where 条件 T1.xx = xxx.....
),
tb3 as (
select * from tb1
union all
select * from tb2
)
select 产编,max(日期) as 最近日期
from tb3
group by 产编
---------------------------------
方法二:
;with tb1 as (
select M.产编,max(T1.日期) as 最近日期
From 资料库Now.table M
Left outer join 资料库Now.Table出货纪录 T1 on M.产编 = T1.产编
Where 条件 T1.xx = xxx.....
group by M.产编
),
tb2 as (
select M.产编,max(T1.日期) as 最近日期
From 资料库2013.table M
Left outer join 资料库2013.Table出货纪录 T1 on M.产编 = T1.产编
Where 条件 T1.xx = xxx.....
group by M.产编
)
select isnull(t1.产编,t2.产编) as 产编,
case when isnull(t1.最近日期,'') > isnull(t2.最近日期,'')
then t1.最近日期
else t2.最近日期
end as 最近日期
from tb1 t1 full join tb2 on t1.产编 = t2.产编
※ 引述《tsongs (......)》之铭言:
: 资料库名称:mssql
: 资料库版本:2008
: 内容/问题描述:
: 因为旧资料被搬到另一个
: 有2资料库 同一个table
: 要取2边最大值
: select M.产编,max(T1.日期) as 最近日期
: From 资料库Now.table M
: Left outer join 资料库Now.Table出货纪录 T1 on M.产编 = T1.产编
: Where 条件 T1.xx= xxx.....
: Group by M.产编
: 资料库Now 改成 资料库2013 也没问题
: 请问能不能直接写在一起直接抓到2边的最大值
: 有 group 不知道怎处理
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 210.61.233.210
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1515738728.A.BCB.html
1F:推 tsongs: 用方法2执行成功 感谢 01/12 15:43
2F:→ tsongs: 如果要加入第3个资料库,ISNULL() AS 产编 会出现问题 01/12 15:45
3F:→ tsongs: 有解吗 还是用方法一来处理 01/12 15:46
4F:推 tsongs: 方法一 3TABLE 跑起来没问题 改用方法一 01/12 15:55