SQLite条件SELECT语句 - 多个条件但单个语句

时间:2016-02-21 17:35:51

标签: sql sqlite select inner-join multiple-columns

我有2个表,一个是客户列表,另一个是这些客户的历史和未来交付日期列表。

创建示例表的便捷代码:

CREATE TABLE Customers (
  id INTEGER PRIMARY KEY AUTOINCREMENT,

  name TEXT
);

INSERT INTO Customers (name) VALUES ('David');
INSERT INTO Customers (name) VALUES ('John');
INSERT INTO Customers (name) VALUES ('Anne');

CREATE TABLE Orders (
  id INTEGER,
  item TEXT,
  delivery_date TEXT
);

INSERT INTO Orders VALUES  ( 1, 'gopro' , '2016-04-05');
INSERT INTO Orders VALUES  ( 1,'car', '2015-12-30');
INSERT INTO Orders VALUES  ( 1,'watch', '2015-10-20');
INSERT INTO Orders VALUES  ( 2, 'laptop', '2016-04-15');
INSERT INTO Orders VALUES  ( 3, 'car', '2016-01-15');
INSERT INTO Orders VALUES  ( 3,'cup', '2015-11-30');

我需要创建一个SQL语句,显示所有客户和他们的最近和下一个交付日期。

(类似于 - 来自拥有最近和下一个项目以及日期来自订单的客户的SELECT *。)

预期结果表

Name, Most Recent Item, Recent Date, Next Item, Next Date
David, car, 2015-12-30, gopro, 2016-04-05
John, NULL, NULL, laptop, 2016-04-15
Anne, car, 2016-01-15, NULL, NULL

但我能用一句话得到的最接近的是:

SELECT
(SELECT o.item from Orders WHERE delivery_date < date('now') ORDER BY delivery_date DESC LIMIT 1) as Last_Item_Ordered,
(SELECT o.delivery_date from Orders WHERE delivery_date < date('now') ORDER BY delivery_date DESC LIMIT 1) as Last_Delivery_Date,
(SELECT o.item from Orders WHERE delivery_date >= date('now') ORDER BY delivery_date ASC LIMIT 1) as Next_Item_Ordered,
(SELECT o.delivery_date from Orders WHERE delivery_date >= date('now') ORDER BY delivery_date ASC LIMIT 1) as Next_Delivery_Date,
c.*
FROM (Orders o INNER JOIN Customers c ON c.id = o.id)
GROUP BY c.name
ORDER BY c.id; 

实际结果如下:

Last_Item_Ordered   Last_Delivery_Date  Next_Item_Ordered   Next_Delivery_Date  id  name
watch        2015-10-20      watch       2015-10-20      1       David
laptop       2016-04-15      laptop      2016-04-15      2       John
cup          2015-11-30      cup         2015-11-30      3       Anne

今天的日期是2016年2月21日,因此对于上述客户未来的结果,预计某些值为NULL。

如果有人可以提供帮助,请不胜感激。感谢

1 个答案:

答案 0 :(得分:3)

您可以使用以下查询:

SELECT (SELECT o.item 
        from Orders AS o 
        WHERE o.id = c.id AND delivery_date < date('now')
        ORDER BY delivery_date DESC LIMIT 1) as Last_Item_Ordered,
       (SELECT o.delivery_date 
        from Orders AS o 
        WHERE o.id = c.id AND delivery_date < date('now')
        ORDER BY delivery_date DESC LIMIT 1) as Last_Delivery_Date,
       (SELECT o.item 
        from Orders AS o 
        WHERE o.id = c.id AND delivery_date >= date('now')
        ORDER BY delivery_date ASC LIMIT 1) as Next_Item_Ordered,
       (SELECT o.delivery_date 
        from Orders AS o 
        WHERE o.id = c.id AND delivery_date >= date('now')
        ORDER BY delivery_date ASC LIMIT 1) as Next_Delivery_Date,
        c.*
FROM Customers c
ORDER BY c.id;

Demo here