I have a SQL Server table Orders
with data as shown here. I need to get counts for particular column based value and calculate sum of those counted columns.
ID | Name | Status | Year
---+--------+---------+------
1 |ckOrder | Success | 2023
2 |psOrder | Failed | 2023
3 |saOrder | Failed | 2022
4 |skOrder | Failed | 2023
5 |pkOrder | NotRun | 2023
6 |plOrder | Success | 2023
7 |poOrder | Null | 2023
Now I want to get each status column with its count as individual column and need to calculate the Total number of Status counts in a separate column as mentioned below.
Result should return values like this:
Success | Failed | NotRun | Total | Year
--------+--------+--------+-------+-----
2 | 3 | 1 | 6 | 2023
0 | 0 | 1 | 1 | 2022
I have tried something with count()
but was not able to make the columns with row values for Status
column in table Orders
. I need some guidance on how to make row values as columns as mentioned with above conditions with grouping of Status
and Year
columns.
3条答案
按热度按时间31moq8wy1#
This query will count the number of orders with each status for each year, and display the results in a table with columns for Success, Failed, NotRun, Total, and Year. The results will be grouped by Year.
sulc1iza2#
try this query:
This will work when you have only 4 types of status.
ou6hu8tu3#
This is the same as the other answers but I added logic to not count nulls in the total count.