gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:58:22 26 4
gpt4 key购买 nike

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

创建示例表的便捷代码:

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 语句来显示所有客户以及他们最近和下一个交货日期。

(类似 - 从客户中选择 * 以及订单中最近和下一个项目和日期。)

预期结果表

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 日,因此对于上述客户的 future 结果,某些值预计为 NULL。

如果有人能提供帮助,我们将不胜感激。谢谢

最佳答案

您可以使用以下查询:

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 语句 - 多个条件但单个语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35539478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com