DEV Community

Judy
Judy

Posted on

3 1 1 1 1

SQL: Perform statistics at different granularities based on the time span of the data #85

A certain view in MS SQL will generate data with different time spans. When the time span is less than 30 days:
Image description
Grouping by branchId and day is required, and the total price should be summed up as follows:
Image description
When the time span is greater than or equal to 30 days and less than 365 days:
Image description
Then group by branchId and month, and sum up the total price. Note: The format remains unchanged, and the output time field is taken as the first day of the current month.
Image description
When the time span is greater than or equal to 365 days:
Image description
Group by branchId and year, also sum up the total price. Note: The time field is taken as the first day of the current year.
Image description
SPL code:
Image description
A1: Query the view through JDBC.

A2: Calculate the time span.

A3: Group and aggregate. When the span is greater than 365 days, the time format mask is yyyy; When the span is less than 30 days, the mask is yyyy-MM-dd, and for other spans, it is set to yyyy-MM. The date function returns the first day of the current year for the yyyy mask time string and the first day of the current month for the yyyy-MM mask time string.

A4: Adjust the field order to meet formatting requirements.

Open source SPL source address

Free Download

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more