用现有的数据划分数据新数据

时间:2017-10-31 18:46:47

标签: sql sql-server

我正在尝试更新已添加到表中的新记录的索引字段。有些记录已经有索引,如何使用下一个值序列更新新记录?

Sample data:
    Index   INCIDENT_DT Incident_type   Event       CITY            COUNTRY
    1       1/2/16 0:00 Accident        Truck       Boston          NULL
    2       1/2/16 0:00 Accident        Car         Boston          NULL
    3       1/2/16 0:00 Accident        Ground      Sutton          USA
            1/2/16 0:00 Accident        NULL        NULL            NULL
            1/2/16 0:00 Accident        NULL        Chicago         NULL

SELECT  ROW_NUMBER() OVER (partition BY  INCIDENT_DT order by  INCIDENT_DT) AS Index, INCIDENT_DT  
FROM  (select distinct  INCIDENT_DT, Incident_type, [event], INCIDENT_CITY, INCIDENT_COUNTRY from input ) r

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

她的一种方法是UNION

SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) [Index],* FROM 
(
    SELECT INCIDENT_DT, Incident_type,   [Event], CITY , COUNTRY FROM <table_name>
    UNION ALL
    SELECT '1/2/16 0:00' [INCIDENT_DT], 'Accident' [Incident_type], NULL [Event],    NULL  CITY, NULL COUNTRY
    UNION ALL
    SELECT '1/2/16 0:00' [INCIDENT_DT], 'Accident' [Incident_type], NULL [Event],    'Chicago'  CITY, NULL COUNTRY
) A

结果:

Index   INCIDENT_DT Incident_type   Event   CITY    COUNTRY
1       1/2/16 0:00 Accident        Truck   Boston  NULL
2       1/2/16 0:00 Accident        Car     Boston  NULL
3       1/2/16 0:00 Accident        Ground  Sutton  USA 
4       1/2/16 0:00 Accident        NULL    NULL    NULL
5       1/2/16 0:00 Accident        NULL    Chicago NULL

答案 1 :(得分:0)

Yogesh感谢您的想法。永远不会想到工会。

这很有用。

SELECT  ROW_NUMBER() OVER (partition BY  INCIDENT_DT order by  grp, index, INCIDENT_DT) AS grp, index, INCIDENT_DT  
FROM  (select distinct 1 as grp, index, INCIDENT_DT, Incident_type, [event], INCIDENT_CITY, INCIDENT_COUNTRY from input where index is not null
union
select distinct 2 as grp, index, INCIDENT_DT, Incident_type, [event], INCIDENT_CITY, INCIDENT_COUNTRY from input where index is null
 ) r