SQLite 条件 SELECT 语句 - 多个条件但单个语句
Posted
技术标签:
【中文标题】SQLite 条件 SELECT 语句 - 多个条件但单个语句【英文标题】:SQLite conditional SELECT statement - multiple criteria but single statement 【发布时间】:2016-06-03 01:02:26 【问题描述】:我有两张表,一张是客户列表,另一张是这些客户的历史和未来交货日期列表。
创建示例表的便捷代码:
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 * from Customers with recent and next item and date FROM Orders.)
预期结果表
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】:您可以使用以下查询:
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
【讨论】:
以上是关于SQLite 条件 SELECT 语句 - 多个条件但单个语句的主要内容,如果未能解决你的问题,请参考以下文章