sqlcountnestedsum

Sum rows that match a condition and the others that dont in the same query


I am trying to summarize in a table all the rows that match a condition as OpenOrder and the ones that dont. For now, I have a query that shows all the conditions

    select count(fk_OrderType)OrderCount, OrderName
from TrainingOrders group by fk_ActionTrainingType

This query shows a table with:

OrderName  OrderCount
A            10
B            5
C            7
D            3

What I want is this:

OrderName   ORderCount
A             10
E             15 (B+C+D)

I tried this

select sum(case when fk_OrderType= 45175 then 1 else 0 end) OpenOrder,
  sum(case when fk_OrderType<> 45175 then 1 else 0 end) NoOpenOrder
from TrainingOrders 

But the result is not what Iam looking for. Someone tall me that I have to use a nested query, but I dont know how to do it. Please, any light in this subject will be greatly appreciated.


Solution

  • I solved this using a pivot table following the example in https://www.sqlshack.com/es/multiples-opciones-para-transponer-filas-en-columnas/

    SELECT *
    FROM
    (
       select JobName,count(fk_OrderType)OrderCount, OrderName
    from TrainingOrders group by fk_ActionTrainingType 
    ) AS SourceTable PIVOT(sum([OrderCount]) FOR [OrderName] IN([A],
                                                             [B],
                                                             [C],
                                                             [D],
                                                             [E])) AS PivotTable 
    order by JobName;