sql查找列的最大值并选择作为新字段

时间:2018-07-25 08:35:11

标签: sql tsql

我目前正在处理一些救护车数据,在某些情况下,多个车辆被调度到同一呼叫。在被派遣的那些人中,有时他们站着(转移到另一个电话。)

相关字段为incidentID, VehicleAllocationSequenceNumber snd VehicleArrivalAtSceneDateTime

incidentID可以映射到具有不同的VehicleAllocationSequenceNumberVehicleArrivalAtSceneDateTime的多行。

VehicleAllocationSequenceNumber定义车辆到达现场的顺序。如果车辆从未到达,VehicleArrivalAtSceneDateTime就是datetime or NULL

我要选择distinct IncidentID's,并将其他列浓缩为两个新功能; Number_of_Vehicles_assignednumber_of_vehicles_on_scene

对于这种复杂性的查询,我还很陌生,我正在寻找一种无需使用游标即可做到这一点的方法。

预先感谢

编辑: 没关系,我提出了疑问,今天早上我只是有点头脑混乱。这是我为后代的查询。

欢迎反馈:

select
    IncidentID,
    max(VehicleAllocationSequenceNumber) as number_vehicles_assigned,
    count(VehicleArrivalAtSceneDateTime) as number_of_vehicles_on_scene
FROM
    [dwuserobj].[acc].[AmbulanceLinkedDatasetForModelling]
where
    IncidentID in(
        select distinct
            IncidentID
        from
            [dwuserobj].[acc].[AmbulanceLinkedDatasetForModelling]
    )
and vehicleArrivalAtSceneDateTime is not null
group by
    IncidentID;

2 个答案:

答案 0 :(得分:0)

import gensim model = gensim.models.KeyedVectors.load_word2vec_format('/home/shikhar /Downloads/GoogleNews-vectors-negative300.bin',binary=True) array=np.zeros((4,300)) for i in test: synonyms=test[i].split(',') case一起使用

not exists

编辑:

所以没有车辆是车辆数量...我的坏消息:

select distinct incidentID,
  case
    when not exists 
        (
        select 1 
        from AmbulanceTable t2 
        where t2.incidentID = t1.incidentID
        and t2.VehicleAllocationSequenceNumber is null
        ) then 1
    else 0 as alloc,
  case
    when not exists 
        (
        select 1 
        from AmbulanceTable t3 
        where t3.incidentID = t1.incidentID
        and t3.VehicleArrivalAtSceneDateTime is null
        ) then 1
    else 0 as onscene
from AmbulanceTable t1

如果未分配/在现场,这将为您提供零

答案 1 :(得分:0)

这应该为您提供所需的逻辑。我制作了一个临时表,以便您可以查看identityID如何与AllocationSequenceNumber和SceneDateTime交互。

DECLARE @AmbulanceLinkedDatasetForModelling TABLE (IncidentID int, VehicleAllocationSequenceNumber int,  VehicleArrivalAtSceneDateTime datetime)
INSERT INTO  @AmbulanceLinkedDatasetForModelling
SELECT 1, 500, NULL UNION ALL  -- the vehicle never arrived
SELECT 2, 501, '2016-05-20 06:07:00.370' UNION ALL
SELECT 3, 502, '2018-01-05 08:15:08.970' UNION ALL
SELECT 4, 503, NULL UNION ALL -- the vehicle never arrived
SELECT 4, 504, '2017-04-11 11:22:01.360'UNION ALL
SELECT 4, 505, '2017-04-11 11:32:01.360'

SELECT 
    IncidentID, 
    number_vehicles_assigned=COUNT(DISTINCT VehicleAllocationSequenceNumber), 
    no_vehicles_on_scene=SUM(CASE WHEN VehicleArrivalAtSceneDateTime IS NOT NULL THEN 1 ELSE 0 END) 
FROM 
    @AmbulanceLinkedDatasetForModelling


GROUP BY
    IncidentID