我的sql数据库中有两个表:
表1中的列:
entity ID, contact person, contact ID, created date
表2中的列:
contact ID entity ID modified date contact person
1 2 10/12/13 MR.A
1 2 11/12/13 MR.B
4 16 17/12/13 MR.C
4 16 19/12/13 MR.D
我想将表2中的记录插入表1,其中修改日期是同一contact ID
的最大值。
输出应该是:
表1 :
entity ID contact person contact ID created date
2 MR.B 1 11/12/13
16 MR.D 4 19/12/13
请建议如何编写这样的SQL查询。我已经使用了一些最大的查询但有但没有得到我的答案,猜猜它没有正确放置?
提前致谢
答案 0 :(得分:2)
看起来你在Table2上没有主键。如果你这样做,这将更容易,因为你可以在连接中使用它。但是,如果不这样,那么这个sql可以解决问题:
INSERT INTO Table1("entity ID", "contact person", "Contact ID", "created date")
SELECT b."entity ID", b."contact person", b."contact ID", b."created date"
FROM
(
SELECT "Contact ID", "entity ID" , MAX("created date") "created date"
FROM Table2
GROUP BY "Contact ID", "entity ID"
) a
JOIN Table2 b ON b."Contact ID" = a."Contact ID" AND
b."entity ID" = a."entity ID" AND
b."created date" = a."created date"
Sql小提琴可以是found here
答案 1 :(得分:0)
你需要学习它,下次试着找到解决方案。
INSERT INTO table_1 (entity_ID, contact_person, contact_ID, created_date)
SELECT entity_ID, contact_person, contact_ID, Max(created date)
FROM table_2
Group by entity_ID, contact_person, contact_ID
答案 2 :(得分:0)
插入table1值(从table2 t22中选择t2.entityid,t2.contactperson,t2.contactid,(选择max(t2.createddate),其中t22.entityid = t2.entityid)来自table2 t2 groupby t2.entityid,t2 .contactperson,t2.contactid)
答案 3 :(得分:0)
使用以下选择查询获取数据,然后插入数据:
select
t1.contact_id, t1.ENTITY_ID, t1.MODIFIED_DATE, t1.CONTACT_PERSON
from
test_table t1,
(select
contact_id, max(modified_date) as max_modified_date
from
test_table
group by
contact_id) t2
where
t1.contact_id = t2.contact_id and t1.MODIFIED_DATE = t2.max_modified_date;
答案 4 :(得分:0)
试试这个:
INSERT INTO Table1 (EntityID,ContactPerson,ContactID,CreatedDate)
SELECT
EntityID,ContactPerson,ContactID,ModifiedDate
FROM
(
Select Row_NUMBER() Over(Partition By ContactId order by ModifiedDate DESC) ROW_NO,
EntityID,ContactPerson,ContactID,ModifiedDate
from Table2
) AS T WHERE T.ROW_NO = 1