1

i'm having this query to get the doubles in a table, but on a different date:

SELECT  acf.ID , acf.ID2 , acf.CNK , acf.Omsch , acf.Groep , acf.prijs
FROM dbo.Acf_LstPrijzen acf
WHERE HstDate = '2013-12-01'
INTERSECT
SELECT  acf.ID , acf.ID2 , acf.CNK , acf.Omsch , acf.Groep , acf.Prijs
FROM dbo.Acf_LstPrijzen acf
WHERE HstDate = (SELECT MAX(acf2.hstDate) 
                         FROM dbo.Acf_LstPrijzen acf2
                         WHERE acf2.HstDate < '2013-12-01'
                         AND acf.id = acf2.id
                         GROUP BY id)

My question is: How can I insert this result in another table? Is it possible?

2
  • yes it's possible. insert into table_X (select ..... ) Jan 8, 2014 at 13:47
  • Duplicate of this and many others.
    – Zane
    Jan 8, 2014 at 14:14

2 Answers 2

3

Try this...

insert into #T

    select * from
    (
    SELECT  acf.ID , acf.ID2 , acf.CNK , acf.Omsch , acf.Groep , acf.prijs
    FROM dbo.Acf_LstPrijzen acf
    WHERE HstDate = '2013-12-01'
    INTERSECT
    SELECT  acf.ID , acf.ID2 , acf.CNK , acf.Omsch , acf.Groep , acf.Prijs
    FROM dbo.Acf_LstPrijzen acf
    WHERE HstDate = (SELECT MAX(acf2.hstDate) 
                             FROM dbo.Acf_LstPrijzen acf2
                             WHERE acf2.HstDate < '2013-12-01'
                             AND acf.id = acf2.id
                             GROUP BY id)
    )
2

I would do something like this:

INSERT INTO TableName (column1,column2,column3,column4,column5,column6)
SELECT t.ID , t.ID2 , t.CNK , t.Omsch , t.Groep , t.prijs
FROM(
SELECT  t.ID , t.ID2 , t.CNK , t.Omsch , t.Groep , t.prijs
FROM dbo.t_LstPrijzen t
WHERE HstDate = '2013-12-01'
INTERSECT
SELECT  t1.ID , t1.ID2 , t1.CNK , t1.Omsch , t1.Groep , t1.Prijs,
FROM    (SELECT  ID, ID2, CNK , Omsch , Groep , Prijs,
        ROW_NUMBER() OVER(PARTITION BY id ORDER BY HstDate DESC) AS rnk
FROM dbo.t_LstPrijzen 
WHERE HstDate < '2013-12-01') t1
WHERE t1.rnk = 1 ) t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.