I’m looking to take a dataset like below and generate some statistics off the data. However, i’m having trouble figuring out how to get the data or if its even possible with a single query. I have different types of ports, in the below example its only user/printer/unknown, but there can be more than just those three. I also have status and again there can be more than just the statuses that are listed. I’ve tried using groupby, but it just doesn’t seem to be the right tool since I’m wanting to group by one type, but I also need a count on each of the statuses?!? Any suggestions on how to achieve this would be greatly appreciated.
| Status | Type
| connected | User
| disabled | User
| connected | Printer
| disabled | Printer
| connected | User
| disabled | Unknown
| disabled | Unknown
Want Resuls like this:
| Type | Connected | Disabled
| User | 2 | 1
| Printer | 1 | 1
| Unknown | 0 | 2
As @JNK mentioned, you can use
PIVOT, but to do it dynamically, I believe you would have to construct the statement based on the available Status values.The example below uses
PIVOTwith hard-coded status values, and then constructs the statement using the values from the sample data. You could also get the Status values from a table of valid statuses, etc.