我试图在连接两个表后选择“ contractkey”。我现在只能运行“ select *”,然后返回所有列。下面是查询。只要我不尝试选择列,它就可以完美运行。如何选择特定的列?我需要在INNER JOIN之后标记表格吗?
Select *
FROM
(SELECT
attachmentdata.contractkey,
requirementinfo.reqcode,
requirementinfo.parentidkey as 'ReqInfoParentID',
max(attachment.datecreated) as datecreated,
applicationinfo.hocompletiondate
FROM location1.attachment
LEFT JOIN location1.attachmentdata
on attachment.contractkey = attachmentdata.contractkey
and attachment.id = attachmentdata.parentidkey --Links Attachment Type
LEFT JOIN location1.requirementinfo
on attachment.contractkey = requirementinfo.contractkey
and attachment.parentidkey = requirementinfo.id --Links Attachment Type
INNER JOIN location1.applicationinfo
on attachment.contractkey = applicationinfo.contractkey
and requirementinfo.parentidkey = applicationinfo.parentidkey --Links Policy Type
where
(requirementinfo.reqcode = 2)
group by attachmentdata.contractkey,requirementinfo.reqcode,
requirementinfo.parentidkey, applicationinfo.hocompletiondate) as table1
INNER JOIN
(SELECT
attachmentdata.contractkey,
requirementinfo.reqcode,
requirementinfo.parentidkey as 'ReqInfoParentID',
attachment.datecreated,
applicationinfo.hocompletiondate,
attachmentdata.pcdata
FROM location1.attachment
LEFT JOIN location1.attachmentdata
on attachment.contractkey = attachmentdata.contractkey
and attachment.id = attachmentdata.parentidkey --Links Attachment Type
LEFT JOIN location1.requirementinfo
on attachment.contractkey = requirementinfo.contractkey
and attachment.parentidkey = requirementinfo.id --Links Attachment Type
INNER JOIN location1.applicationinfo
on attachment.contractkey = applicationinfo.contractkey
and requirementinfo.parentidkey = applicationinfo.parentidkey)table2
on table1.contractkey = table2.contractkey
and table1.reqcode = table2.reqcode
and table1.ReqInfoParentID = table2.ReqInfoParentID
and table1.datecreated = table2.datecreated
and table1.hocompletiondate = table2.hocompletiondate
答案 0 :(得分:1)
两个表中都有contractkey
列,因此系统不知道您要哪个列。因此,您必须将表名放在其前面。
SELECT table1.contractkey, ...
答案 1 :(得分:0)
在您最外面的内部表选择的末尾添加以下内容:
SELECT contractkey FROM
(SELECT
attachmentdata.contractkey,
etc...
) AS t(contractkey,reqcode,ReqInfoParentID,datecreated,hocompletiondate)
答案 2 :(得分:0)
不需要“标记表格”(别名)。用例确保对于不在AttachmentData表中的记录,它不会为空,如下所示:
Select * FROM
(SELECT case
WHEN attachmentdata.contractkey IS NOT NULL THEN attachmentdata.contractkey
else attachment.contractkey END AS contractkey,
requirementinfo.reqcode,
requirementinfo.parentidkey as 'ReqInfoParentID',
max(attachment.datecreated) as datecreated,
applicationinfo.hocompletiondat
...