I wish to SUM
the COUNT
of a query as follows. This query returns the count properly (1) for each row, but not sure how to add them all up.
SELECT COUNT(*), jss_orders_headers.* FROM jss_orders_headers
LEFT JOIN jss_orders_extrafields
ON jss_orders_headers.orderID = jss_orders_extrafields.orderID
AND jss_orders_extrafields.extraFieldID = 5
GROUP BY jss_orders_headers.orderID
ORDER BY jss_orders_headers.orderID DESC
Table Structure is
orderID, etc
exid, orderID, extrafieldID, extrafieldName, content
This currently returns data as follows:
1 | 99
1 | 104
1 | 106
I need to return the SUM
of the COUNT()
column. So in the 3 examples above I would return 3
.
Many thanks
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.
The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.
SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group.
SUM() function with group by MySQL SUM() function retrieves the sum value of an expression which has undergone a grouping operation by GROUP BY clause.
Your question is not exactly clear but if you only want the sum()
of all orders
, then you should be able to use something like this:
select sum(TotalByOrder) TotalOrders
from
(
SELECT COUNT(*) TotalByOrder, jss_orders_headers.*
FROM jss_orders_headers
LEFT JOIN jss_orders_extrafields
ON jss_orders_headers.orderID = jss_orders_extrafields.orderID
AND jss_orders_extrafields.extraFieldID = 5
GROUP BY jss_orders_headers.orderID
) src
Would WITH ROLLUP
do what you need?
SELECT COUNT(*), jss_orders_headers.* FROM jss_orders_headers
LEFT JOIN jss_orders_extrafields
ON jss_orders_headers.orderID = jss_orders_extrafields.orderID
AND jss_orders_extrafields.extraFieldID = 5
GROUP BY jss_orders_headers.orderID DESC WITH ROLLUP
Why there's no ORDER BY
?
When you use ROLLUP, you cannot also use an ORDER BY clause to sort the results. In other words, ROLLUP and ORDER BY are mutually exclusive. However, you still have some control over sort order. GROUP BY in MySQL sorts results, and you can use explicit ASC and DESC keywords with columns named in the GROUP BY list to specify sort order for individual columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With