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

时间:2018-05-14 04:35:55

标签: sql sql-server sql-server-ce

如何在多个表中使用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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

另一种方法是再次将整个查询包装在表中并放入条件。喜欢以下查询。

 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