如何避免选择查询中的空值,并在不在表中的选择查询中将该值替换为0?

时间:2016-07-17 05:57:18

标签: mysql sql

select t1.d as Date,t1.S AS StoreNo ,t1.Cash,N3.price,(N3.price-t1.Cash)as Totalsale,ISNUll(t2.gift,0)as Card,ISNULL(t3.coupon,0) as couup
from 
(Select Date as d,StoreNo as S,SUM(DayTotalAmt)Cash
  from POS_FinTtl where (SerialNo like  '23')
  group by StoreNo,SerialNo,Date) t1 

Join (Select Date as d,StoreNo as S, SUM(DayTotalAmt)gift
      from POS_FinTtl where (SerialNo like  '31')
      group by StoreNo,SerialNo,Date) t2 On t1.d =t2.d and t1.S = t2.S
join (Select Date as d,StoreNo as S, SUM(DayTotalAmt)coupon
      from POS_FinTtl where (SerialNo like  '30')
      group by StoreNo,SerialNo,Date)t3 On t2.d =t3.d and t2.S = t3 
Left join (Select BuyDate as d,StoreNo as S ,Sum(SalePrice)as price 
           from POS_TtlTran where StoreNo = 467 
           GROUP BY StoreNo,BuyDate) As N3
        On  N3.d = t1.d and N3.S = t1.S
        Where (N3.S = 467) AND (N3.d >= '6/01/2015') AND (t1.d <= '6/30/2015')



Result 

Date        StoreNo Cash  price  Totalsale Card  couup

2015-06-01  467     14860 88145  73285    78334  2000

2015-06-05  467     23032 76380  53348    40456  19000

2015-06-07  467     44225 133737 89512    95205  5000

2015-06-14  467     78134 110940 32806    30677  11000

2015-06-21  467     76234 166070 89836    97114  6000

2015-06-23  467     19844 46221  26377    29072  1000

2015-06-28  467     91165 127911 36746    40974  6000

但是日期2015-06-02 couup值0但是它不是从表中提取而是从其他列中提取值。

2 个答案:

答案 0 :(得分:0)

有许多事情要使用,它们都在manual中。对于表达式IFNULL(var,0)中的条件替换,如果它具有值,则返回var。

答案 1 :(得分:0)

您应该使用条件聚合。基本查询是:

widget.padding = [ (self.textinput.width - width of line) / 2, 20, 0, 0]

我并不完全遵循日期算术的适用方式 - 要么在Select Date as d, StoreNo as S, SUM(case when SerialNo like '23' then DayTotalAmt else 0 end) as cash, SUM(case when SerialNo like '31' then DayTotalAmt else 0 end) as gift, SUM(case when SerialNo like '30' then DayTotalAmt else 0 end) as coupon, SUM(case when StoreNo = 467 then SalePrice else 0 end) as price from POS_FinTtl group by StoreNo, Date; 子句中应用于所有值,要么应用于单个where语句中。无论走到哪里,您都不需要这么复杂的查询。