简体   繁体   中英

Insert specific number of records with same column value into a different table

Let's say I have two tables, tblProducts and tblPromoItems , that will both contain the same record types. For simplification sake, suppose each record only has two attributes, ID and creation_date . How would I take records from tblProducts and insert into tblPromoItems , such that only n total records are inserted and there are only i instances of records with the same creation_date ?

For example, using the below table how would I insert a total of 3 records, given the condition that there can be at most 2 records with the same creation_date .

tblProducts

ID| creation_date

A | 2014-12-01

B | 2014-12-01

C | 2014-12-01

D | 2014-12-02

You can use row_number() with a common table expression to get 2 records per date:

with cte as (
  select *, 
    row_number() over (partition by cast(creation_date as date) 
                       order by creation_date desc) rn
  from tblProducts
  )
select * 
from cte
where rn <= 2

I'm not quite sure what you mean by only n total records can be inserted. Presumably you want to limit the number of inserts into the table? One way is to use top for that -- select top 100 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM