If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > ANSI SQL > How to do it in one insert statement? Please come in

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-09-04, 16:43
ted2000 ted2000 is offline
Registered User
 
Join Date: Sep 2003
Posts: 3
Post How to do it in one insert statement? Please come in

Back from the vacation, I find I can't remember something. My problem is, for example, I have 2 tables. Table 1 has 3 columns: id, saledate and amount. Table 2 has just 2 columns: id and amount. Now I want to select the latest 'amount' for each 'id' from table 1 and insert into empty table 2. Is that possible to do it in one insert statement? What's the best way to do it anyways?

Thanks a lot!
Reply With Quote
  #2 (permalink)  
Old 01-09-04, 16:53
gyuan gyuan is offline
Registered User
 
Join Date: Dec 2003
Posts: 454
In your table1, is id the primary key?
Reply With Quote
  #3 (permalink)  
Old 01-09-04, 16:57
ted2000 ted2000 is offline
Registered User
 
Join Date: Sep 2003
Posts: 3
No, id and saledate are primary key. Any thoughts? Thanks anyways.
Reply With Quote
  #4 (permalink)  
Old 01-09-04, 20:22
gyuan gyuan is offline
Registered User
 
Join Date: Dec 2003
Posts: 454
In the Table1, do you have a primary key from one colomn, i.e., TableID?
Reply With Quote
  #5 (permalink)  
Old 01-10-04, 06:17
r123456 r123456 is offline
Registered User
 
Join Date: Sep 2003
Location: The extremely Royal borough of Kensington, London
Posts: 778
insert into table2
select id, max(amount)
from table1 t1
where saledate = (select max(saledate) from table1 where id = t1.id)
group by id;

The "max(amount)" and "group by id" return the maximum amount, should multiple amounts exist for the latest salesdate for a given id.
__________________
Bessie Braddock: Winston, you are drunk!
Churchill: And Madam, you are ugly. And tomorrow, I'll be sober, and you will still be ugly.
Reply With Quote
  #6 (permalink)  
Old 01-12-04, 10:32
ted2000 ted2000 is offline
Registered User
 
Join Date: Sep 2003
Posts: 3
Thumbs up Thanks!

Yes, it works! Thanks a lot!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On