ORDER BY句では取得結果の並び順を指定できます。SELECT文とともに利用します。
並び替えに使いたい列を指定しつつ並び順をDESC(降順)かASC(昇順)で指定します。
ORDER BY句の基本構文
SELECT 列名 FROM 表名 ORDER BY 列名 DESC もしくは ASC
AlaSQLでの記述例
let sales = [
{id:1, item_id:1, price:200, cost:50, created:'2020-6-12 10:00:00' },
{id:2, item_id:1, price:180, cost:50, created:'2020-6-12 11:00:00' },
{id:3, item_id:1, price:250, cost:60, created:'2020-6-13 10:00:00' },
{id:4, item_id:1, price:200, cost:60, created:'2020-6-13 14:00:00' },
{id:5, item_id:1, price:150, cost:60, created:'2020-6-13 18:00:00' },
];
let result = alasql("SELECT "
+ "item_id, "
+ "price, "
+ "cost, "
+ "(price - cost) AS profit "
+ "FROM ? "
+ "ORDER BY price DESC"
,[sales]);
console.log(result);
実行結果
0: {item_id: 1, price: 250, cost: 60, profit: 190}
1: {item_id: 1, price: 200, cost: 50, profit: 150}
2: {item_id: 1, price: 200, cost: 60, profit: 140}
3: {item_id: 1, price: 180, cost: 50, profit: 130}
4: {item_id: 1, price: 150, cost: 60, profit: 90}
ORDER BY句で複数指定の例
複数の列を指定することも可能です。
SELECT * FROM sales ORDER BY cost DESC, price DESC
実行結果
0: {item_id: 1, price: 150, cost: 60, profit: 90}
1: {item_id: 1, price: 180, cost: 50, profit: 130}
2: {item_id: 1, price: 200, cost: 50, profit: 150}
3: {item_id: 1, price: 200, cost: 60, profit: 140}
4: {item_id: 1, price: 250, cost: 60, profit: 190}