6.7 Alignment grouping by ordinal number: keep one record at most for each group

 

Sort data by the order of specified ordinal numbers and keep one matching member at most for each group. This is suitable for viewing and using data according to the specified order.

Query sales records according to the order from Monday to Sunday based on the daily sales table. Below is part of the table:

Week Day Amount
5 Sunday 1101.2
5 Saturday 538.6
5 Friday 2142.4
5 Thursday 1456.0
5 Wednesday 48.0
5 Tuesday 1376.0
5 Monday 676.0
4 Sunday 448.0
4 Saturday 4031.0
4 Friday 364.8

SPL uses A.align(n,y) function to perform alignment grouping. The operation divides records into n groups (from 1 to n) and calculate ordinal number of the group each record belongs through grouping expression y. By default, one matching member at most is retained for each group.

SPL script:

A
1 =T(“DailySales.csv”)
2 [“Monday”,“Tuesday”,“Wednesday”,“Thursday”,“Friday”,“Saturday”,“Sunday”]
3 =A1.group(Week; ~.align(7,A2.pos(Day)):WeekSales)
4 =A3.conj(WeekSales)
5 =A4.select(~)

A1 Query the DailySales table.
A2 Define a sequence of days from Monday to Sunday.
A3 To group sales records by week, use A.align(n,y) function to align sales records of each week to the order of sequence defined in A2. Note that an alignment grouping operation may result in one or more empty groups. For instance, when there are no sales records on Friday and Saturday in the second week, the operation will still generate seven groups for each week, as shown below:

Week
[2,Monday,1194.0]
[2,Tuesday,1622.4]
[2,Wednesday,319.2]
[2,Thursday,802.0]
(null)
(null)
[2,Sunday,2123.2]

A4 Concatenate sorted sales records of all weeks.
A5 Select non-null records from A4’s result set.

Execution result:

Week Day Amount
1 Monday 3063.0
1 Tuesday 3868.6
1 Wednesday 2713.5
1 Thursday 1005.9
1 Friday 1675.0
1 Saturday 400.0
1 Sunday 2018.2
2 Monday 1194.0
2 Tuesday 1622.4
2 Wednesday 319.2