请查看以下查询:
tbl_EASY_INVOICECONTROLDB.dbo.impersonalaccount
departmentname accountid accountname accounttype
------------------------------------------------------------
Football Club 82425 Consultancy G/L Account
Stadium Ltd 82425 Professional fees G/L Account
tbl_documents4.dbo.GLcodetable2
username item department
------------------------------------------------------
RAY 82425 otrUserSettingsGLcodes_Stadium
RAY 82425 otrUserSettingsGLcodes
查询
SELECT
A.item, A.username, A.department,
B.departmentname, B.accounttype, B.accountname
FROM
dbo.GLcodetable2 AS A
LEFT OUTER JOIN
EASY_INVOICECONTROLDB.dbo.impersonalaccount AS B ON A.item = B.accountid
WHERE
(A.item = '82425') AND (A.username = 'RAY')
结果:
item username department departmentname accountype accountname
---------------------------------------------------------------------------------------------------------------------
82425 RAY otrUserSettingsGLcodes Football Club G/L Account Consultancy
82425 RAY otrUserSettingsGLcodes_Stadium Football Club G/L Account Consultancy
82425 RAY otrUserSettingsGLcodes Stadium Ltd G/L Account Professional fees
82425 RAY otrUserSettingsGLcodes_Stadium Stadium Ltd G/L Account Professional fees
某些数据线出现了两次。
我正在尝试将两个表连接在一起,并获得每个部门名称的一个结果。
我试过GROUP BY
,但这似乎不起作用。
提前谢谢。
修改
我正在寻找的结果是
item username department departmentname accountype accountname
-----------------------------------------------------------------------------------------------------------------------------
82425 RAY otrUserSettingsGLcodes Football Club G/L Account Consultancy
82425 RAY otrUserSettingsGLcodes_Stadium Stadium Ltd G/L Account Professional fees
答案 0 :(得分:0)
如果您需要两个表中的所有列,那么您将获得四个记录,但如果您从部门列中删除,那么您将获得基于部门名称的两个记录。试试这样,我在你的查询中评论了部门专栏。
SELECT
A.item,
A.username,
--A.department,
B.departmentname,
B.accounttype,
B.accountname
FROM @GLcodetable2 AS A
LEFT OUTER JOIN @impersonalaccount AS B ON A.item = B.accountid
WHERE (A.item = '82425') AND (A.username = 'RAY')
group by A.item,
A.username,
--A.department,
B.departmentname,
B.accounttype,
B.accountname
答案 1 :(得分:0)
根据要求,您可以检查在连接条件中添加部门
ON A.ItemID = B.AccountID AND A.department = B.departmentName