SQL联合查询

时间:2011-03-11 05:35:26

标签: sql sql-server tsql union

SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
FROM tblPAppointments pa INNER JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
WHERE pv.Status = 0
GROUP BY pv.PropertyID

UNION ALL

SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
FROM tblPAppointments pa INNER JOIN tblJobVisits jv ON jv.AppID = pa.AppID
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID

我需要在两个单独的列中获取InitialVisit count和JobVisit count.above query只返回两列(PropertyID,InitialVisit)。

2 个答案:

答案 0 :(得分:4)

使用NULL作为不占任何输出的列的占位符:

  SELECT pv.PropertyID, 
         COUNT(pv.VisitID) AS InitialVisit,
         NULL AS jobvisit
    FROM tblPAppointments pa 
    JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
   WHERE pv.Status = 0
GROUP BY pv.PropertyID
UNION ALL
  SELECT jv.PropertyID, 
         NULL AS initialvisit,
         COUNT(jv.JobVistID) AS JobVisit
    FROM tblPAppointments pa 
    JOIN tblJobVisits jv ON jv.AppID = pa.AppID
   WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID

这将返回三列。列别名在第一个查询中是必需的,但在第二个查询中不是 - 我将两者都别名以明确发生了什么。

请注意,在SQL Server中使用NULL这样的NULL将要求您对NULL以外的数据类型使用CAST/CONVERT,因为SQL Server将NULL默认为INT数据类型(奇怪的是)

不使用UNION的备用查询:

   SELECT x.propertyid,
          COUNT(y.visitid) AS initialvisit,
          COUNT(z.jobvisitid) AS jobvisit
     FROM (SELECT pv.propertyid
             FROM TBLPROPERTYVISIT pv
            WHERE EXISTS (SELECT NULL
                            FROM TBLAPPOINTMENTS a 
                           WHERE a.appid = pv.appid)
           UNION 
           SELECT jv.propertyid
             FROM TBLJOBVISIT jv
            WHERE EXISTS (SELECT NULL
                            FROM TBLAPPOINTMENTS a 
                           WHERE a.appid = jv.appid)) x
LEFT JOIN TBLPROPERTYVISIT y ON y.propertyid = x.propertyid
LEFT JOIN TBLJOBVISIT z ON z.propertyid = x.propertyid
 GROUP BY x.propertyid

答案 1 :(得分:3)

根本不需要UNION。而且你不使用tblPAppointments

编辑以允许其中一个表中没有行。仍然有一行输出

SELECT
    ISNULL(pv2.PropertyID, jv2.PropertyID),
    ISNULL(pv2.InitialVisit, 0),
    ISNULL(jv2.JobVisit, 0)
FROM
    (
    SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
    FROM tblPropertyVisit pv
    WHERE pv.Status = 0
    GROUP BY pv.PropertyID
    ) pv2
    FULL OUTER JOIN
    (
    SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
    FROM tblJobVisits jv
    WHERE jv.VisitStatus = 1
    GROUP BY jv.PropertyID
    ) jv2 ON pv2.PropertyID = jv2.PropertyID