I have one table with multiple columns. I am needing to create an SQL query to display certain columns based off of the user input from a datepicker and a select box. I have done that just fine. However, I am needing one of the result columns to be totaled at the bottom of the display table. I cannot figure out how to create a result within my current query to display the totaled column. Essentially, I would like the WTTotal column to be totaled into a separate cell. My current query is below. I really think this is something simple that I just can't seem to see.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
UNION ALL
SELECT 'Total', NULL, NULL, NULL, NULL, SUM(WTTotal)
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL;
You can't have it with a single query. Putting a SUM()
into your query would require a GROUP BY
clause and collapse all of your original result rows down into a single result row - meaning your table would disappear. What you want a is a client-side solution. e.g. Start a counter in your client code and manually add up the results. In pseudoish-code:
$sum = 0;
while( $row = fetch_from_db() ) {
$sum += $row['field_to_sum'];
display_row();
}
echo "Total: $sum";
If you want to have it in a separate column, not in a separate row, either you calculate it in a subquery and join it to your result:
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, my_calculated_sum AS WTTotal
FROM WorkTicket
JOIN (SELECT SUM(whatever_you_want_to_sum) as my_calculated_sum FROM WorkTicket) subquery_alias
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
Or you just calculate it with variables, like a running total. Your result is in the last row of the column.
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy, @sum_variable := @sum_variable + whatever_you_want_to_sum AS WTTotal
FROM WorkTicket
, (SELECT @sum_variable := 0) var_init_subquery
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
ORDER BY Client
But actually Kevin's solution is very good.
I also have similar solution as Kevin's :
;with cte_result
as
(
SELECT REPLACE(Client,',',' ') AS Client,WorkTicketNum,Lease,Date,OrderedBy,WTTotal
FROM WorkTicket
WHERE Date BETWEEN '2014-10-01' AND '2014-10-31' AND Invoiced IS NULL
)
select *
from cte_result
union
select 'TotalAmount',NULL,NULL,NULL,NULL,sum(WTTotal)
from cte_result
order by client
but this solution will work only if your DB Engine supports CTE. with a CTE, we can use same resultset to get total's row.