如何选择在sql中使用相同的id插入哪一行?

时间:2012-05-31 23:31:29

标签: sql ssis

所以基本上我有一个名为“table_1”的表:

ID   Index          STATUS          TIME        DESCRIPTION
1     15          pending           1:00       Started Pending
1     16          pending           1:05       still in request
1     17          pending           1:10       still in request
1     18          complete          1:20       Transaction has been completed
2     19          pending           2:25       request has been started
2     20          pending           2:30       in progress
2     21          pending           2:35       in progess still
2     22          pending           2:40       still pending
2     23          complete          2:45       Transaction Compeleted

我需要将这些数据插入到我的第二个表“table_2”中,其中只包含start和compelete时间,所以我的“table_2”应该是这样的:

ID   Index   STATUS          TIME          DESCRIPTION
1     15     pending         1:00          Started Pending
1     18     complete        1:20          Transaction has been completed
2     19     pending         2:25          request has been started
2     23     complete        2:45          Transaction Compeleted

如果有人可以帮我写sql查询,我会非常感激。 提前致谢

4 个答案:

答案 0 :(得分:2)

INSERT INTO t2 (ID, STATUS, TIME)
SELECT ID, STATUS, MIN(TIME) FROM t1 t1top
WHERE EXISTS(SELECT * FROM t1 WHERE ID=t1top.ID AND STATUS='Complete')
GROUP BY ID, STATUS
ORDER BY CAST(ID AS UNSIGNED) ASC, STATUS DESC

插入完成后,如果要根据示例查看结果,则必须运行以下选择:

SELECT ID, STATUS, TIME FROM table_1
ORDER BY CAST(ID AS UNSIGNED) ASC, STATUS DESC

那是完全正确的,但我不想只是这样看待它,它也需要以这种方式插入第二个表格,任何想法?

答案 1 :(得分:1)

INSERT INTO table_2
SELECT id,status,min(time)
FROM table_1 AS t1
WHERE EXISTS(SELECT 1
             FROM table_1
             WHERE id=t1.id
                 AND status='complete')
GROUP BY id,status

我认为应该为你做,但是没有测试过:(

答案 2 :(得分:0)

你可以得到 所有的开始时间都是这样的:

   select id, status, min(time) 
   from table_1 
   where status = 'Pending'
   group by id, status

然后像这样完成:

   select id, status, time
   from table_1 
   where status = 'Complete'
   group by id, status

你可以使用union来同时使用它们,当然可以尝试:

   insert into table_2

答案 3 :(得分:0)

INSERT INTO myTable2 (ID, STATUS, TIME, DESCRIPTION)
SELECT t1.ID, t1.STATUS, t1.TIME, t1.DESCRIPTION FROM table_1 as t1 
WHERE STATUS = 'complete' 
OR TIME = (SELECT min(TIME) FROM table_1 WHERE ID = t1.ID) 
ORDER BY ID asc, STATUS desc