SQLServer 语句怎么写
A表和B表的都有address、time、value三列,现在需要从A表和B表获取每个address的time值最大的value值然后将address、time、valu...
A表和B表的都有address、time、value三列,现在需要从A表和B表获取每个address的time值最大的value值然后将address、time、value 输出,请问这条SQL语句怎么写?
展开
2个回答
展开全部
嵌套比较多,你慢慢看。
select D.address, D.time, D.value
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B) D,
(select C.Address, max(C.time) as maxTime
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B) C
group by C.address) E
where D.address = E.address
and D.time = E.maxTime
select D.address, D.time, D.value
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B) D,
(select C.Address, max(C.time) as maxTime
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B) C
group by C.address) E
where D.address = E.address
and D.time = E.maxTime
更多追问追答
追问
佩服,能写出视图方式的吗?我是要把B、C、D三个表的内容分别于A表的相应字段进行上述操作
追答
CREATE OR REPLACE VIEW VW_MAX AS
select G.address, G.time, G.value
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B
union
select C.address, C.time, C.value
from C
union
select D.address, D.time, D.value
from D) G,
(select E.Address, max(E.time) as maxTime
from (select A.address, A.time, A.value
from A
union
select B.address, B.time, B.value
from B
union
select C.address, C.time, C.value
from C
union
select D.address, D.time, D.value
from D) E
group by E.address) F
where G.address = F.address
and G.time = F.maxTime
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
--2个表自己合并下就好
SELECT *
FROM (SELECT address,time,value,ROW_NUMBER () OVER (PARTITION BY address ORDER BY time DESC) AS N FROM 表1) AS A
WHERE N=1;
追问
这个方法只能找到表A或者表B的数据吧,怎么样将两个表的最大值汇聚一个表格?
能写出视图方式的吗?我是要把B、C、D三个表的内容分别于A表的相应字段进行上述操作
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询