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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay