Function: GROUP BY
Purpose
The GROUP BY
function in Wonderful Relations is used to aggregate query results by grouping them based on a specific field or a condition. This is similar to SQL’s GROUP BY
, allowing structured aggregation of data, especially when working with summarized reports, statistics, or grouped listings.
Unlike WHERE
, which filters before aggregation, GROUP BY
structures the result after selection, grouping similar records together.
Parameters
- Field – The column used for grouping results.
- Condition – A custom condition used for grouping when no direct field is available.
Field
The Field parameter specifies the column by which the data should be grouped. This is typically an ID or a categorical field.
Example:
SELECT id, SUM(hours) as total_hours
FROM wp_your_project_table
GROUP BY id;
Condition
Here, the grouping is based on a custom condition, categorizing entries as Active Projects or Inactive Projects instead of using a direct field.
SELECT
CASE
WHEN status = 'active' THEN 'Active Projects'
ELSE 'Inactive Projects'
END as project_status,
COUNT(*) as total_count
FROM wp_your_project_table
GROUP BY project_status;
Default Grouping in DataTables
For Wonderful Relations DataTables, queries on the top level automatically add a GROUP BY id
if they contain joins or subqueries to ensure that each record remains unique.
Conclusion
The GROUP BY function in Wonderful Relations allows for flexible and efficient data aggregation, whether using standard fields or dynamic conditions. By leveraging custom conditions, complex grouping scenarios can be handled seamlessly without modifying the base query structure. 🚀