-2

如何将这 2 个查询合并为一个查询并...

select  cp.TouchedWhen,
        U.DisplayName AS 'ATTENDING'
from    SXAAMBClientPrescription CP (nolock)
    inner join CV3User U (nolock) on U.GUID = CP.CareproviderGUID
Order by CP.TouchedWhen ASC

select  cp.TouchedWhen,
        U.DisplayName AS 'RESIDENT'
from SXAAMBClientPrescription CP (nolock)
        inner join CV3User U (nolock) on U.GUID = CP.UserGUID
order by CP.TouchedWhen ASC

输出应该是:

TouchedWhen | Attending | Resident

9/16/13     | Dr Joe    | Resident Schmo

如果 TouchedWhen 在 2 个查询中匹配,则参加者和居民应该像上面一样在同一行中。否则填写主治人员和居民,但他们出现。

谢谢你。

4

4 回答 4

1
SELECT cp.TouchedWhen
     , U1.DisplayName As ATTENDING
     , U2.DisplayName As RESIDENT
FROM   SXAAMBClientPrescription As CP (NOLOCK)
 LEFT
  JOIN CV3User As U1 (NOLOCK)
    ON U1.GUID = CP.CareproviderGUID
 LEFT
  JOIN CV3User As U2 (NOLOCK)
    ON U2.GUID = CP.UserGUID
ORDER
    BY CP.TouchedWhen ASC

TouchedWhen即使没有匹配的UserGUIDor ,这也会为每个返回一行CareproviderGUID。如果您只想要两者的结果,只需将连接类型更改为INNER

于 2013-09-16T20:41:38.767 回答
0

您也可以 UNION 都选择:

SELECT TouchedWhen, MIN(ATTENDING), MIN(RESIDENT)
FROM
 (
   SELECT  cp.TouchedWhen,
           U.DisplayName AS 'ATTENDING'
           CAST(NULL AS VARCHAR(40) AS 'RESIDENT'
   FROM    SXAAMBClientPrescription CP (nolock)
       INNER JOIN CV3User U (nolock) ON U.GUID = CP.CareproviderGUID
   UNION ALL    
   SELECT  cp.TouchedWhen,
           CAST(NULL AS VARCHAR(40) AS 'ATTENDING'
           U.DisplayName AS 'RESIDENT'
   FROM SXAAMBClientPrescription CP (nolock)
           INNER JOIN CV3User U (nolock) ON U.GUID = CP.UserGUID
 ) as dt
GROUP BY TouchedWhen
ORDER BY 1 ASC
于 2013-09-16T20:47:00.183 回答
0

您可以使用完全外连接:

select cp.TouchedWhen, t1.ATTENDING, t2.RESIDENT
from 
(select  cp.TouchedWhen AS TouchedWhen,
        U.DisplayName AS ATTENDING
from    SXAAMBClientPrescription CP (nolock)
    inner join CV3User U (nolock) on U.GUID = CP.CareproviderGUID
Order by CP.TouchedWhen AS) t1

FULL OUTER JOIN     
(select  cp.TouchedWhen AS TouchedWhen,
        U.DisplayName AS RESIDENT
from SXAAMBClientPrescription CP (nolock)
        inner join CV3User U (nolock) on U.GUID = CP.UserGUID
order by CP.TouchedWhen ASC) t2

on t1.TouchedWhen = t2.TouchedWhen;
于 2013-09-16T20:41:01.140 回答
0

如果您不介意没有attendingresident删除where子句的行:

select  
    cp.TouchedWhen,
    u.DisplayName as 'ATTENDING',
    r.DisplayName as 'RESIDENT'
from
    SXAAMBClientPrescription cp (nolock)
        left outer join 
    CV3User u (nolock) 
        on u.GUID = cp.CareproviderGUID
        left outer join
    CV3User r (nolock) 
         on r.GUID = cp.UserGUID
where
    u.guid is not null or
    r.guid is not null
order by 
    cp.TouchedWhen
于 2013-09-16T20:41:40.857 回答