请进!,求数据合并的SQL语句!

duoshanx 2003-11-18 09:28:21
A区消费单

userID year pay1
3707123 2001 100
3707123 2002 200

B区消费单

userID year pay2
3707123 2003 3000
3707123 2002 2000

想做view,结果如下:

userId year pay1 pay2
3707123 2001 100
3707123 2002 200 2000
3707123 2003 3000

...全文
21 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
duoshanx 2003-11-18
  • 打赏
  • 举报
回复
我第二个方法做的太麻烦了,好处只有一个,可以不分isnull的顺序,但没有用:)
再次感谢3.0!
pengdali 2003-11-18
  • 打赏
  • 举报
回复
第二个麻烦些。

select isnull(isnull(a.userID,b.userID),c.userid) userID,isnull(isnull(a.[year],b.[year]),c.[year]) [year],a.pay1,b.pay2,c.pay3 from A区消费单 a full join B区消费单 b on a.userID=b.userID and a.[year]=b.[year] full join C区消费单 c on a.userID=c.userID and a.[year]=c.[year]
duoshanx 2003-11-18
  • 打赏
  • 举报
回复
SELECT ISNULL(a.userId, ISNULL(c.userId, b.userId)) AS userID, ISNULL(a.[year],
ISNULL(c.[year], b.[year])) AS year, a.pay1, b.pay2, c.pay3
FROM dbo.bb b FULL OUTER JOIN
dbo.cc c ON b.userId = c.userId AND b.[year] = c.[year] FULL OUTER JOIN
dbo.aa a ON c.[year] = a.[year] AND c.userId = a.userId AND b.userId = a.userId AND
b.[year] = a.[year]

这是三个表!
duoshanx 2003-11-18
  • 打赏
  • 举报
回复
如果是多个表的话,是不是用第二个方法(select isnull.....)不行呢?

我是多个表,用的是第一个方法

duoshanx 2003-11-18
  • 打赏
  • 举报
回复
谢谢!十分的感谢! !!!!
已经是3.0了?
563 ?!
靠!晕!
pengdali 2003-11-18
  • 打赏
  • 举报
回复
或:

select isnull(a.userID,b.userID) userID,isnull(a.[year],b.[year]) [year],a.pay1,b.pay2 from A区消费单 a full join B区消费单 b on a.userID=b.userID and a.[year]=b.[year]
pengdali 2003-11-18
  • 打赏
  • 举报
回复
select userID,[year],sum(pay1) pay1,sum(pay2) pay2 from (
select userID,[year],pay1,null pary2 from A区消费单
union all
select userID,[year],null pay1,pary2 from B区消费单) tem group by userID,[year]
pengdali 2003-11-18
  • 打赏
  • 举报
回复
select userID,[year],sum(pay1) pay1,sum(pay2) pay2 from (
select userID,[year],pay1,null pary2 from A区消费单
union all
select userID,[year],null pay1,pary2 from A区消费单) tem group by userID,[year]

34,829

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧