Reputation: 1210
I have a table named VehicleAlerts, you can see in the below image that there are different type AlertSubCategory such as Pickup/Drop Delay ,Vehicle Stalled ,Vehicle Speeding Geofence Violation. How will I get count of all type of AlertSubCategory of a vehicle?
Upvotes: 0
Views: 62
Reputation: 192
SELECT AlertSubCategory,COUNT(*) as norow FROM VehicleAlerts group by AlertSubCategory
Upvotes: 0
Reputation: 194
If you want to get the count of all vehicles in each AlertSubCategory then you can simple group it by AlertSubCategory and take the count as given below.
SELECT AlertSubCategory, COUNT(Id) AS Count
FROM VehicleAlerts
GROUP BY AlertSubCategory
If you want to get the cout of one vehicle in each AlertSubCategory then use a WHERE clause in this sql query as given below.
DECLARE @VehicleId INT = 1
SELECT AlertSubCategory, COUNT(Id) AS Count
FROM VehicleAlerts
WHERE Vehicle = @VehicleId
GROUP BY AlertSubCategory
Change the value of @VehicleId as you required.
Upvotes: 0
Reputation: 3684
A simple Count
with a Group By
on both VehicleId and AlertSubCategory will get the data
SELECT VehicleId, AlertSubCategory, Count(1) Occurrence
FROM [table]
GROUP BY VehicleId, AlertSubCategory
Upvotes: 0
Reputation: 93734
Use Conditional Count
to do this
SELECT vehicleid,
P_D_delay_count = Count(CASE
WHEN alertsubcategory = 'pickup/drop delay' THEN 1
END) AS,
VehicleStalled = Count(CASE
WHEN alertsubcategory = 'VehicleStalled' THEN 1
END),
VehicleSpeeding = Count(CASE
WHEN alertsubcategory = 'VehicleSpeeding' THEN 1
END),
Geofence_Violation_count = Count(CASE
WHEN alertsubcategory = 'Geofence Violation' THEN 1
END)
FROM yourtable
GROUP BY vehicleid
Upvotes: 1