根据sqlserver中的字段从master表中获取值

时间:2018-03-23 06:36:33

标签: sql sql-server sql-server-2008

我想根据事务表的不同col值

从master表中检索值

我的master表格会有username,FirstName,lastName

我的transaction表格会有Id,CreatedUser,UpdatedUser

所以我希望查询从sql server获取报告,从createruser的master表中获取FirstName,lastName,并从updateuser获取master表中的FirstName,lastName。

例: 主表

User ID First Name  Last Name
cer001  Ds  CV
cer002  vb  av

交易表

id  CreatedUser UdatedUser
2323    cer001  cer002

所以报告应该得到像

这样的结果
Id  CreatedUser UpdatedUSer
2323    Ds,CV   Vb,av

它应该是表现明智也好。请帮忙解决这个问题

3 个答案:

答案 0 :(得分:1)

您正在寻找self join

select 
      t.Id, m.FirstName +','+m.LastName as  CreatedUser,
      mm.FirstName +','+mm.LastName as  UpdatdUser
from Master m
inner join Transaction  t on t.CreatedUser = m.[User ID]
inner join Master mm on mm.[User ID]= t.UpdatedUser 

答案 1 :(得分:0)

您应该尝试从事务表到主表的左连接。 LEFT来处理任何NULL值

<强> see working demo

查询将是

structure(list(Count_ID = c(123L, 123L, 123L, 456L, 456L, 789L, 
486L, 486L), Stats = c("A", "A", "B", "B", "C", "A", "A", "A"
), Date = c("10/01/2017", "12/01/2017", "15/01/2017", "18/01/2017", 
"17/01/2017", "20/01/2017", "25/01/2017", "28/01/2017")), .Names = c("Count_ID", 
"Stats", "Date"), class = "data.frame", row.names = c(NA, -8L
))

答案 2 :(得分:0)

也许你可以尝试使用下面的子查询

Select
 t.id,
 (Select TOP 1 Rtrim(m.[First Name])+','+RTRIM(m.[Last Name]) from [Master] m where m.[User ID] = t.CreatedUser) as CreatedUser,
  (Select TOP 1 Rtrim(m.[First Name])+','+RTRIM(m.[Last Name]) from [Master] m where m.[User ID] = t.UpdatedUser) as UpdatedUser
from [Transaction] t