如何从sql中的相同列计算不同的值?

时间:2015-12-12 10:25:17

标签: sql sql-server sql-server-2008

我有一张名为VehicleAlerts的表, 你可以在下图中看到有不同类型的AlertSubCategory,例如Pickup / Drop Delay,Vehicle Stalled,Vehicle Speeding Geofence Violation。我如何计算车辆的所有类型的AlertSubCategory?

enter image description here

4 个答案:

答案 0 :(得分:1)

使用Conditional Count执行此操作

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 

答案 1 :(得分:0)

VehicleId和AlertSubCategory上都有Count的简单Group By将获取数据

SELECT VehicleId, AlertSubCategory, Count(1) Occurrence
FROM   [table]
GROUP BY VehicleId, AlertSubCategory

答案 2 :(得分:0)

如果您想获得每个AlertSubCategory中所有车辆的计数,那么您可以通过AlertSubCategory对其进行简单分组,并计算如下所示的计数。

SELECT AlertSubCategory, COUNT(Id) AS Count
FROM VehicleAlerts
GROUP BY AlertSubCategory

如果你想在每个AlertSubCategory中获得一辆车的cout,那么在这个sql查询中使用WHERE子句,如下所示。

DECLARE @VehicleId INT = 1
SELECT AlertSubCategory, COUNT(Id) AS Count
FROM VehicleAlerts
WHERE Vehicle = @VehicleId 
GROUP BY AlertSubCategory

根据需要更改@VehicleId的值。

答案 3 :(得分:0)

选择AlertSubCategory,COUNT(*)作为NOTS FROM VehicleAlerts group by AlertSubCategory