在SQL中需要手动增加Insert

时间:2013-12-12 20:22:12

标签: sql sql-server tsql

我有以下查询,但没有为ActionId正确增加

   insert into CorrAction (AlertId, Action, ActionId)

    select b.alertID,   a.Action, b.ActionId = (Select isnull(max(CorrectiveActionId),0) + 1 from CorrAction where alertid = b.alertId) 

    FROM 

    (select requestDate, action, tag from #alert ) a 

    INNER JOIN 

    (select alertdate, tag, alertId from #RetroAlert ) b 

    on Convert(date,a.requestdate) = Convert(date,b.alertdate) and a.tag = b.tag

我遇到的问题是ActionId没有正确增加。

应该执行以下操作:

AlertId    ActionId
------     --------
2344       1 
2344       2
3455       1
5344       1
3432       1

请注意,如果AlertId存在重复条目,则应增加1.否则应为1.

我的查询中发生的事情始终是1

2 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER功能。 这是一个简化的查询,因为我不知道表格的结构。

SELECT
  AlertId,
  alertdate,
  (SELECT ISNULL(MAX(actionId), 0) FROM CorrAction AS c WHERE c.AlertId = t.AlertId) 
  + ROW_NUMBER() OVER (PARTITION BY AlertId ORDER BY alertdate DESC) AS ActionId
FROM TempTable AS t;

这里有一个示例:http://sqlfiddle.com/#!3/0d1d30/5

编辑:更新了我的示例,以便从已插入CorrAction表中的最高actionId开始计数。

答案 1 :(得分:0)

使用行号功能,以便查询可以正常工作

insert into CorrAction (AlertId, Action, ActionId)
select b.alertID,   a.Action,  row_number() Over  (partition by alertId  order by CorrectiveActionId) as ActionId
FROM 
(select requestDate, action, tag from #alert ) a 
INNER JOIN 
(select alertdate, tag, alertId from #RetroAlert ) b 
on Convert(date,a.requestdate) = Convert(date,b.alertdate) and a.tag = b.tag
inner join CorrAction C
on C.alertid =b.alertId