android - sql语句中同一个查询的多个case和order_by?

标签 android sql sqlite

我对 SQL 进行了相当复杂的搜索,在尝试使用多个案例进行查询几次尝试后,我想知道是否可以在一个查询中完成所有操作,或者我是否需要拆分任务。

invoices 表包括 customer_id、customer_version、startDate (DateTime) 和 status。

这是目标:

From invoices,
when customer_id='123' and customer_version="321" select invoice according to status.

if there are one or more past_due invoices, pick the older one.

if there is no past_due invoice, pick the first open invoice,

if there is no open invoice, pick the last paid invoice,

if there is no paid invoice, pick the future invoice,

if there is no future invoice, pick the last draft,

if there is no draft, then retrieve a null value for all invoice.

是否可以在同一个 SELECT sql phrase 中使用不同的 startDate 顺序(ASC、DESC)检查空值并按状态进行查询?谁能举个例子?

最佳答案

首先,为所有这些情况创建示例,并根据它们的预期优先级对它们进行正确排序:

status    date
--------------
past_due   d1
past_due   d2
open       d1
open       d2
paid       d2
paid       d1
future     ?
draft      d2
draft      d1

然后,分配数字,以便 ORDER BY status2, date2 可以正常工作。 (如果我们假设日期是数字,则 -d2 小于 -d1,即取反会反转排序方向。)

status    date  status2  date2
------------------------------
past_due   d1      1      d1
past_due   d2      1      d2
open       d1      2      d1
open       d2      2      d2
paid       d2      3     -d2
paid       d1      3     -d1
future     ?       4      ?
draft      d2      5     -d2
draft      d1      5     -d1

然后使用CASE expressions将状态值映射到这些数字,并相应地修改日期。 (如果日期值采用受支持的格式,julianday() 将返回一个数字;儒略日的实际含义并不重要,只要它们相互正确比较即可。)

SELECT customer_id,
       customer_version,
       startDate,
       status
FROM invoices
WHERE customer_id = 123
  AND customer_version = '321'
ORDER BY CASE status
           WHEN 'past_due' THEN 1
           WHEN 'open'     THEN 2
           WHEN 'paid'     THEN 3
           WHEN 'future'   THEN 4
           WHEN 'draft'    THEN 5
         END,
         CASE
           WHEN status IN ('past_due', 'open', 'future')
           THEN  julianday(startDate)  -- earliest date first
           ELSE -julianday(startDate)  -- latest date first
         END
LIMIT 1

LIMIT 1 然后仅返回这些已排序行中的第一行(如果已找到)。

关于android - sql语句中同一个查询的多个case和order_by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28224776/

相关文章:

java - NoClassDefFoundError - Alchemy API

java - 振动直到按下按钮,当按钮未按下(或手指离开)时停止振动

java - 需要知道碰撞何时开始和结束 box2d

sql - 如何在 SQL 中根据匹配百分比比较两个字符串

sqlite - PowerAMC和SQLite

android - 阻止 Android 应用在 Windows 11 上运行

sql - 使用 HAVING 查找恰好一行满足条件的时间

sql日期选择

android - 如何在 SQLite 中使用 FTS3

使用嵌套 SELECT 的 SQLite 查询