将多个表列连接到多个表

时间:2017-02-08 16:18:13

标签: sql sql-server reporting-services

自从我使用SSRS和SQL已经好几年了,所以我提前为这个补救措辞和措辞不好的问题道歉。

我有一个表,事件,包括2列,开启者和所有者(都是整数)。这些列与User表相关,我想从中检索用户名。我可以加入表格,但是如何检索用户名作为开场白和所有者,以便我可以将其包含在我的报告中?

SELECT
    TST_INCIDENT.OPENER_ID AS Logged_By,
    TST_INCIDENT.OWNER_ID AS Assignee,
    TST_INCIDENT.INCIDENT_ID AS Defect_ID,
    TST_INCIDENT.NAME AS Defect_Title,
    TST_INCIDENT.DESCRIPTION AS Defect_Desc,
    TST_USER.USER_NAME
FROM
    TST_USER
INNER JOIN 
    TST_INCIDENT ON TST_USER.USER_ID = TST_INCIDENT.OPENER_ID 
                 AND TST_USER.USER_ID = TST_INCIDENT.OWNER_ID

1 个答案:

答案 0 :(得分:0)

您可以为每个ID加入一次用户表。如果ID可能丢失,请将它们更改为左连接。

SELECT
  TST_INCIDENT.OPENER_ID AS Logged_By
  ,TST_INCIDENT.OWNER_ID AS Assignee
  ,TST_INCIDENT.INCIDENT_ID AS Defect_ID
  ,TST_INCIDENT.NAME AS Defect_Title
  ,TST_INCIDENT.DESCRIPTION AS Defect_Desc
  ,A.USER_NAME as OPENER_USER_NAME
  ,B.USER_NAME as OWNER_USER_NAME
FROM TST_INCIDENT
INNER JOIN TST_USER A ON A.USER_ID = TST_INCIDENT.OPENER_ID 
INNER JOIN TST_USER B ON B.USER_ID = TST_INCIDENT.OWNER_ID