Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/221.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android sql语句中同一查询的多个case和order_by?_Android_Sql_Sqlite - Fatal编程技术网

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

Android sql语句中同一查询的多个case和order_by?,android,sql,sqlite,Android,Sql,Sqlite,我对SQL有一个相当复杂的搜索,在尝试使用多个案例进行查询后,我想知道是否可以在一个查询中完成所有任务,或者是否需要拆分任务 表发票包括客户id、客户版本、起始日期(日期时间)和状态等。 这就是目标: From invoices, when customer_id='123' and customer_version="321" select invoice according to status. if there are one or more past_due invoices, pic

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

发票
包括客户id、客户版本、起始日期(日期时间)和状态等。

这就是目标:

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.

是否可以使用不同的起始日期顺序(ASC、DESC)查询案例,检查空值并按状态选择,同时
选择sql短语
?有人能举个例子吗?

首先,为所有这些情况创建示例,并按预期优先级正确排序:

status    date
--------------
past_due   d1
past_due   d2
open       d1
open       d2
paid       d2
paid       d1
future     ?
draft      d2
draft      d1
然后,分配编号,以便
按状态2排序,日期2
可以正常工作。 (如果我们假设日期是数字,
-d2
小于
-d1
,即,对其求反将反转排序方向。)

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

LIMIT 1
然后只返回这些排序行中的第一行(如果找到了任何行)

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
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