我使用以下方法将3个表中的选择列连接到新表中:
SELECT A.ExternalID, A.UserDefinedXml.value('(Skin_Sheet/@Label)[1]', 'varchar(3)') AS SS, A.ServiceSiteUid, A.LastModifiedDate, A.PersonUid,
B.FirstName, B.LastName, B.PersonUid,
C.Name
FROM Patient A
INNER JOIN Person B ON B.PersonUid = A.PersonUid
INNER JOIN ListServiceSite C ON C.ServiceSiteUid = A.ServiceSiteUid
WHERE SS IS NOT NULL
ORDER By LastModifiedDate;
这一切都有效,但是我不确定如何引用从XML提取的数据创建的列SS
,因此我只能选择值为“是”或“否”的观察值。在R中,我会创建一个新对象,但是如果不指定表名,我不确定SQL如何存储该新表。
请注意,我确实尝试将其插入到新表中,但是SQL不允许我这样做,因为由于某种原因,联接导致PersonUid
被复制。
预先感谢您,我对SQL非常新手,并希望随时学习。
答案 0 :(得分:3)
从概念上讲,WHERE在SELECT之前,因此您需要将查询推送到派生表子查询或公用表表达式(CTE)中,以在WHERE子句中引用SS
。 EG
with q as
(
SELECT A.ExternalID, A.UserDefinedXml.value('(Skin_Sheet/@Label)[1]', 'varchar(3)') AS SS, A.ServiceSiteUid, A.LastModifiedDate, A.PersonUid,
B.FirstName, B.LastName, B.PersonUid,
C.Name
FROM Patient A
INNER JOIN Person B ON B.PersonUid = A.PersonUid
INNER JOIN ListServiceSite C ON C.ServiceSiteUid = A.ServiceSiteUid
)
SELECT *
FROM q
WHERE SS IS NOT NULL
ORDER By LastModifiedDate;
答案 1 :(得分:0)
这会将您的结果放入临时表中,并且避免了两列具有相同名称的问题:
SELECT
A.ExternalID
,SS = A.UserDefinedXml.value('(Skin_Sheet/@Label)[1]', 'varchar(3)')
,A.ServiceSiteUid
,A.LastModifiedDate
,PersonUid_A = A.PersonUid
,B.FirstName
,B.LastName
,PersonUid_B = B.PersonUid
,C.Name
INTO #TempResults
FROM Patient A
INNER JOIN Person B ON B.PersonUid = A.PersonUid
INNER JOIN ListServiceSite C ON C.ServiceSiteUid = A.ServiceSiteUid
WHERE SS IS NOT NULL
ORDER BY LastModifiedDate;