Ordering
Start by importing:
import scalaql._
// Docs classes
import scalaql.docs.Hogwarts._
Usually, sorting scala collections is simple, but it looks awkwardly when it comes to descending ordering.
To sort this by age in descending order, you should do the following:
students.sortBy(_.age)(Ordering[Int].reverse)
// res0: List[Student] = List(
// Student(
// name = "Harry",
// age = 19,
// faculty = "Gryffindor",
// grade = 85.1,
// specialization = "getting into troubles",
// birthDay = 1980-07-31
// ),
// Student(
// name = "Ron",
// age = 18,
// faculty = "Gryffindor",
// grade = 66.2,
// specialization = "eating",
// birthDay = 1980-05-01
// ),
// Student(
// name = "Hermione",
// age = 18,
// faculty = "Gryffindor",
// grade = 99.6,
// specialization = "learning",
// birthDay = 1979-09-17
// ),
// Student(
// name = "Draco",
// age = 18,
// faculty = "Slytherin",
// grade = 85.1,
// specialization = "trolling",
// birthDay = 1980-06-05
// ),
// Student(
// name = "Cedric",
// age = 17,
// faculty = "Hufflepuff",
// grade = 90.1,
// specialization = "young dying",
// birthDay = 1977-10-01
// )
// )
Additionally sorting by name in ascending order looks even more awkwardly:
students.sortBy(s => (s.age, s.name))(Ordering.Tuple2(Ordering[Int].reverse, Ordering[String]))
// res1: List[Student] = List(
// Student(
// name = "Harry",
// age = 19,
// faculty = "Gryffindor",
// grade = 85.1,
// specialization = "getting into troubles",
// birthDay = 1980-07-31
// ),
// Student(
// name = "Draco",
// age = 18,
// faculty = "Slytherin",
// grade = 85.1,
// specialization = "trolling",
// birthDay = 1980-06-05
// ),
// Student(
// name = "Hermione",
// age = 18,
// faculty = "Gryffindor",
// grade = 99.6,
// specialization = "learning",
// birthDay = 1979-09-17
// ),
// Student(
// name = "Ron",
// age = 18,
// faculty = "Gryffindor",
// grade = 66.2,
// specialization = "eating",
// birthDay = 1980-05-01
// ),
// Student(
// name = "Cedric",
// age = 17,
// faculty = "Hufflepuff",
// grade = 90.1,
// specialization = "young dying",
// birthDay = 1977-10-01
// )
// )
Scala QL simplifies this a lot! Just take a look:
val query = select[Student].orderBy(_.age.desc, _.name)
// query: Query[From[Student], Student] = FROM(Hogwarts::Student) -> ORDER BY(Tuple2[+Int,+String])
query
.show(truncate = false)
.run(from(students))
// +--------+---+----------+-----+---------------------+----------+
// |name |age|faculty |grade|specialization |birthDay |
// +--------+---+----------+-----+---------------------+----------+
// |Harry |19 |Gryffindor|85.1 |getting into troubles|1980-07-31|
// |Draco |18 |Slytherin |85.1 |trolling |1980-06-05|
// |Hermione|18 |Gryffindor|99.6 |learning |1979-09-17|
// |Ron |18 |Gryffindor|66.2 |eating |1980-05-01|
// |Cedric |17 |Hufflepuff|90.1 |young dying |1977-10-01|
// +--------+---+----------+-----+---------------------+----------+
//