从包含EXCEPT的查询中计算行

时间:2016-06-24 19:05:57

标签: sql sql-server-2008 coalesce

我有以下查询:

SELECT * 
FROM
    (SELECT 
         SREF, DELIVERYDATE, DATEIDENTIFIED, DCID, SUPN, PONUMBER,
     FROM 
         BNHEAD 
     WHERE 
         (SUPP = 'Sanchez') AND (STAT = '2')

     EXCEPT

     SELECT 
         SREF, DELIVERYDATE, DATEIDENTIFIED, DCID, SUPN, PONUMBER,
     FROM 
         BNHEAD 
     WHERE 
         (SUPP = 'sanchez') 
         AND (STAT = '2') 
         AND ((STI = 'Yes') AND (RESN = 'third party')) 
          OR (FORWARDEDTO = 'STI')) t1
ORDER BY 
    DeliveryDate DESC

如何仅从此查询获取行计数,如果为零则返回0?我认为它可能需要涉及合并,但我不确定如何。

1 个答案:

答案 0 :(得分:4)

您只需在外部查询中使用select count(*)

select count(*)
from (select sref . . .
      . . .
     ) t

select count(*)总是返回一行(当没有group by时)。如果子查询中没有行,它将返回0