1.3 把日期变成小整数
将日期转换成小整数后能获得更好的存储和计算性能。
1.3.1 转储时转换
SPL 提供了一种很省空间的方法,用 days@o(date) 把年月转换成距离 1970 年起的月数,而日用 5 个二进制位表示(一个月最多 31 天,5 位二进制数可以表示 0-31 之间的数),即相当于 ((yyyy-1970)*12+(mm-1))*32+dd,这样就可以用小整数表示从 1970 年到 2140 年间的日期。
SPL 支持直接用 year(int),month(int),day(int) 获得上述转换结果的年月日分量,方便需要年月日分量的汇总计算。
A | |
---|---|
1 | =file(“Orders.txt”).cursor@t(CustomerID:string, OrderDate:datetime, ProductID:string, Quantity:int, Unit:string, Price:decimal, Amount:decimal, EmployeeID:int,EmployeeName:string,ShipVia:string).run(OrderDate=days@o(OrderDate)) |
2 | =file(“Orders.ctx”).create@y(CustomerID,OrderDate,ProductID, Quantity, Unit, Price, Amount, EmployeeID,EmployeeName,ShipVia) |
3 | =A2.append(A1) |
4 | =A2.close() |
A1 修改 OrderDate 为小整数
1.3.2 用转换后的数据计算
SQL
SELECT *
FROM Orders
WHERE OrderDate>='2022-01-01' and OrderDate<='2022-03-15'
SPL
A | |
---|---|
1 | >st=date(“2022-01-01”), et=date(“2022-03-15”), start=days@o(st), end=days@o(et) |
2 | =file(“Orders.ctx”).open().cursor@mx(;OrderDate>=start && OrderDate<end).run(OrderDate=date@o(OrderDate)) |
3 | =A2.fetch() |
A1 把参数 start,end 转成小整数
A2 把结果集中的 OrderDate 转回日期值
SQL
SELECT sum(Amount) Amount,year(OrderDate) years,month(OrderDate) months
FROM Orders
WHERE OrderDate>='2022-01-01'
GROUP BY year(OrderDate),month(OrderDate)
ORDER BY years,months
SPL
A | |
---|---|
1 | >st=date(“2022-01-01”), start=days@o(st) |
2 | =file(“Orders.ctx”).open().cursor@mx(OrderDate,Amount;OrderDate>=start) |
3 | =A2.groups(year(OrderDate):years,month(OrderDate):months; sum(Amount):Amount) |
A3 按年、月分组汇总,可以直接用 year(int),month(int) 获得转换后日期小整数的年月分量
SQL
SELECT EmployeeID,sum(Amount) Amount
FROM Orders
WHERE OrderDate>='2022-01-01' and OrderDate<='2022-03-31'
GROUP BY EmployeeID
ORDER BY EmployeeID
SPL
A | |
---|---|
1 | >st=date(“2022-01-01”), et=date(“2022-03-31”), start=days@o(st), end=days@o(et) |
2 | =file(“Orders.ctx”).open().cursor@mx(EmployeeID, Amount; OrderDate>=start && OrderDate<end) |
3 | =A2.groups(EmployeeID;sum(Amount):Amount) |
SQL
SELECT quarter(OrderDate) quart,sum(Amount) Amount
FROM Orders
WHERE OrderDate>='2022-01-01'
GROUP BY quarter(OrderDate)
SPL
A | |
---|---|
1 | > st=date(“2022-01-01”), start=days@o(st) |
2 | =file(“Orders.ctx”).open().cursor@mx(OrderDate,Amount;OrderDate>=start) |
3 | =A2.groups(month(OrderDate)\3+1:Quarter; sum(Amount):Amount) |