Not quite sure what you’re trying to get the percentage of, but I’ll assume you want something like the percentage of MaintTech1Hours of the total hours.
SQL can do the math for you. In MySQL your select would become something like SELECT Category, SUM (MaintTech1Hours + MaintTech2Hours + MaintTech3Hours + MaintTech4Hours + MaintTech5Hours) AS 'Hours', concat(format(100 * MaintTech1Hours / 'Hours', 0), '%') AS 'Maint Tech 1 %'
This would give you the percent with zero decimal places and a % sign after the number. Once you’ve aliased that sum to Hours, you can refer to it again in other places in your query.
[edit] Whelp, MySQL allows this kind of reference but gives 0 as a result. :shakesfist:
Unless something is different in MySQL 8.0, you cannot refer to an alias in this way, you have to assign it to a variable which isn’t allowed in the JDBC driver. Assigning a value in a query would have to be done database side as a stored procedure.
Select Category,
Hours,
100.0*Hours/(SUM(Hours) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) As Pct
FROM (
Select Category, SUM(MaintTech1Hours + MaintTech2Hours + MaintTech3Hours + MaintTech4Hours + MaintTech5Hours) Hours
From WorkOrder (nolock)
Where DateTm Between DATEADD(month, DATEDIFF(month, 0, getDate()), 0) and DATEADD(month, DATEDIFF(month, -1, getDate()), -1)
Group by Category
) subq
I had to add the “Order by Category” before ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Thanks a lot for the help!
Select Category,
Hours,
100.0*Hours/(SUM(Hours) OVER (Order by Category ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING))Percentage
FROM (
Select Category, SUM(MaintTech1Hours + MaintTech2Hours + MaintTech3Hours + MaintTech4Hours + MaintTech5Hours) Hours
From WorkOrder (nolock)
Where DateTm Between DATEADD(month, DATEDIFF(month, 0, getDate()), 0) and DATEADD(month, DATEDIFF(month, -1, getDate()), -1)
Group by Category
) subq