按行在 SQLite 中使用 SQL 对 return 数据进行排序

sort return data with SQL in SQLite order by row

我有一个有8列的数据库,都是1~99范围内的整数:

Col1    Col2    Col3    Col4    Col5    Col6    Col7    Col8
1       13      24      18      35      7       50      88
13      4       33      90      78      42      26      57
22      18      30      3       57      90      71      8

...

当我执行“select Col1、Col2、Col3、Col5、Col6、Col7、Col8 来自 MyTable,其中 Col4>10” 我希望对 return 数据进行排序,例如第一行应该 return 像这样:

1,7,13,24,35,50,88

但是,“order by”只适用于“Column”,在 SQL 中是否可以执行此操作?或者需要临时 table/max() 来执行此操作?谢谢

注册

林志峰

修复您的数据模型!您不应该在列中存储值。您应该将它们存储在行中。

也就是说,SQL 不对列进行“排序”。它处理行中的数据!

您可以通过将数据反透视成行、计算新顺序然后重新聚合来做您想做的事:

with t as (
      select row_number() over () as id,
             t.*
      from mytable t
      where col4 > 10
     )
select max(case when seqnum = 1 then col end) as col1,
       max(case when seqnum = 2 then col end) as col2,
       max(case when seqnum = 3 then col end) as col3,
       max(case when seqnum = 4 then col end) as col4,
       max(case when seqnum = 5 then col end) as col5,
       max(case when seqnum = 6 then col end) as col6,
       max(case when seqnum = 7 then col end) as col7,
       max(case when seqnum = 8 then col end) as col8
from (select row_number() over (partition by id order by col) as seqnum,
             x.*
      from (select id, col1 as col from t union all
            select id, col2 as col from t union all
            select id, col3 as col from t union all
            select id, col4 as col from t union all
            select id, col5 as col from t union all
            select id, col6 as col from t union all
            select id, col7 as col from t union all
            select id, col8 as col from t
           ) x
     ) x
group by id;

您当前的设计不适合此要求。
考虑将其更改为如下内容:

CREATE TABLE tablename (
  id INTEGER, -- corresponds to the rowid of your current table 
  col_id INTEGER NOT NULL, -- 1-8, corresponds to the number of each of the columns ColX 
  value INTEGER NOT NULL  -- corresponds to the value of each of the columns ColX  
);

您可以根据当前的 table:

填充它
INSERT INTO tablename (id, col_id, value)
SELECT rowid, 1, Col1 FROM MyTable UNION ALL
SELECT rowid, 2, Col2 FROM MyTable UNION ALL
SELECT rowid, 3, Col3 FROM MyTable UNION ALL
SELECT rowid, 4, Col4 FROM MyTable UNION ALL
SELECT rowid, 5, Col5 FROM MyTable UNION ALL
SELECT rowid, 6, Col6 FROM MyTable UNION ALL
SELECT rowid, 7, Col7 FROM MyTable UNION ALL
SELECT rowid, 8, Col8 FROM MyTable

现在您可以通过 GROUP_CONCAT() window 函数和聚合获得您想要的结果:

SELECT result
FROM (
  SELECT id, GROUP_CONCAT(value) OVER (PARTITION BY id ORDER BY value) result
  FROM tablename
  WHERE id IN (SELECT id FROM tablename WHERE col_id = 4 AND value > 10)
)
GROUP BY id
HAVING MAX(LENGTH(result))

参见demo
结果:

result
1,7,13,18,24,35,50,88
4,13,26,33,42,57,78,90