SQLite IFNULL在公式

时间:2018-06-13 18:36:30

标签: sqlite isnull

有时 SUM(c.Quantity)为null所以我需要将其转换为0,尝试使用case / isnull等等,但它在此公式中不起作用。

SELECT (t.LastMonthBalance + IFNULL(SUM(c.Quantity), 0) - t.Balance) * 100.0 / (t.EndMileage - t.StartMileage) AS Result 
FROM TripSheet AS t, Cheque AS c 
WHERE t.VehicleId = 8 
      AND t.Date = '2018-05' 
      AND c.VehicleId = 8 
      AND c.Date BETWEEN '2018-05-01' AND '2018-05-31';

2 个答案:

答案 0 :(得分:0)

我认为您的问题不在于ifnull,而是其他值为空

e.g。正在运行(数量为空): -

DROP TABLE IF EXISTS Tripsheet;
DROP TABLE IF EXISTS Cheque;
CREATE TABLE If NOT EXISTS Tripsheet (VehicleId INTEGER, DATE TEXT, Balance REAL, EndMileage INTEGER, StartMileage , LastMonthBalance REAL);
CREATE TABLE IF NOT EXISTS Cheque (Vehicleid INTEGER, date TEXT, Quantity REAL);
INSERT INTO Tripsheet VALUES(8,'2018-05',50,200,100,200);
INSERT INTO Cheque VALUES(8,'2018-05-02',null);

SELECT (t.LastMonthBalance + IFNULL(SUM(c.Quantity), 0) - t.Balance) * 100.0 / (t.EndMileage - t.StartMileage) AS Result 
FROM TripSheet AS t, Cheque AS c 
WHERE t.VehicleId = 8 
      AND t.Date = '2018-05' 
      AND c.VehicleId = 8 
      AND c.Date BETWEEN '2018-05-01' AND '2018-05-31';

导致 150.0

使用额外的支票条目运行: -

INSERT INTO Cheque VALUES(8,'2018-05-03',25.00);

导致 175.0

但是,如果其他值为null,例如LastMonthBalance,则结果将为null。

所以也许你想要这样的东西: -

SELECT (IFNULL(t.LastMonthBalance,0) + IFNULL(SUM(c.Quantity), 0) - IFNULL(t.Balance,0)) * 100.0 / IFNULL((t.EndMileage - t.StartMileage),100) AS Result 

在哪种情况下: -

DROP TABLE IF EXISTS Tripsheet;
DROP TABLE IF EXISTS Cheque;
CREATE TABLE If NOT EXISTS Tripsheet (VehicleId INTEGER, DATE TEXT, Balance REAL, EndMileage INTEGER, StartMileage , LastMonthBalance REAL);
CREATE TABLE IF NOT EXISTS Cheque (Vehicleid INTEGER, date TEXT, Quantity REAL);
INSERT INTO Tripsheet VALUES(8,'2018-05',null,null,null,null);
INSERT INTO Cheque VALUES(8,'2018-05-02',null);

SELECT (IFNULL(t.LastMonthBalance,0) + IFNULL(SUM(c.Quantity), 0) - IFNULL(t.Balance,0)) * 100.0 / IFNULL((t.EndMileage - t.StartMileage),100) AS Result 
FROM TripSheet AS t, Cheque AS c 
WHERE t.VehicleId = 8 
      AND t.Date = '2018-05' 
      AND c.VehicleId = 8 
      AND c.Date BETWEEN '2018-05-01' AND '2018-05-31';

导致 0.0 而不是null,就像原始SQL产生的那样。

答案 1 :(得分:0)

是的,其他值为null。但要解决它,我必须使用LEFT JOIN和GROUP BY子句更改查询。的解决方案:

SELECT (t.LastMonthBalance + IFNULL(SUM(c.Quantity), 0.0) - t.Balance) * 100 / (t.EndMileage - t.StartMileage) AS Result
FROM TripSheet AS t LEFT JOIN Cheque as c ON t.VehicleId = c.VehicleId
WHERE t.Date = '2018-05' AND t.VehicleId = 1
GROUP BY t.VehicleId;

谢谢Lukasz和MikeT。