1个输出中的2个查询

时间:2013-09-16 20:31:47

标签: mysql sql

如何将这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

如果在2个查询中匹配,则Attending和Resident应与上面的行相同。否则填写出席和居民,但他们出现。

谢谢。

4 个答案:

答案 0 :(得分: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

即使没有匹配的TouchedWhenUserGUID,也会为每个CareproviderGUID返回一行。如果您只希望结果,只需将联接类型更改为INNER

答案 1 :(得分:0)

您可以使用FULL OUTER JOIN:

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;

答案 2 :(得分: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

答案 3 :(得分: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