在多个表中使用 union all 时如何删除空行

How to remove null rows in when using union all in multiple tables

如何在多个表中使用 union all 时删除空行

declare @FromDate date='2018-05-01';
    declare @ToDate date='2018-05-10';

    select ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS [SNO],t.MNO,MNAME ,isnull(sum(v1),0.00) as Balance,isnull(sum(v2),0.00) as CurrentPurchase,isnull(sum(v3),0.00) as Deduction
    from (select MNO, PendingDeduc as v1, NULL as v2, NULL as v3
          from tblProductPurchaseBalance where EntryDate between @FromDate and @ToDate union all
          select MNO, NULL as v1, TotalAmount, NULL as v3
          from tblMnoProductPurchase where PurchaseDate between @FromDate and @ToDate union all
          select MemNo as MNO, NULL as v1, NULL as v2, AAVIN
          from tblDeduction where EntryDate between @FromDate and @ToDate       
         ) t inner join TBLMEMBERS on t.MNO=TBLMEMBERS.MNO
    group by t.MNO,MNAME
    order by t.MNO

Sample Data And Result I need

您不能在您的 where 子句中使用 t.Balance > 0,因为 Balance 只是您在 select.

中的列的别名

您可以在 GROUP BY 之后写 HAVING isnull(sum(v1),0.00) > 0

您的最终查询应如下所示。

SELECT ..., isnull(sum(v1),0.00) Balance
FROM
(
 --Your internal query here
) T
GROUP BY t.MNO,MNAME
HAVING isnull(sum(v1),0.00) > 0

另一种方法是再次将整个查询包装在 table 中并放入条件。就像下面的查询。

 select * from
 ( 
 select ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS [SNO],t.MNO,MNAME ,isnull(sum(v1),0.00) as Balance,isnull(sum(v2),0.00) as CurrentPurchase,isnull(sum(v3),0.00) as Deduction
    from (select MNO, PendingDeduc as v1, NULL as v2, NULL as v3
          from tblProductPurchaseBalance where EntryDate between @FromDate and @ToDate union all
          select MNO, NULL as v1, TotalAmount, NULL as v3
          from tblMnoProductPurchase where PurchaseDate between @FromDate and @ToDate union all
          select MemNo as MNO, NULL as v1, NULL as v2, AAVIN
          from tblDeduction where EntryDate between @FromDate and @ToDate       
         ) t inner join TBLMEMBERS on t.MNO=TBLMEMBERS.MNO
    group by t.MNO,MNAME
   )t
   where T.Balance > 0 OR T.CurrentPurchase > 0 OR T.Deduction > 0
   order by t.MNO

根据需要的结果在外部查询中使用任何聚合函数。它会解决你的问题。例如求和函数。